Dive in the deep

Encoder / Decoder

Unlike JSON encoder / decoder at pytmongo, mongoengine_goodjson passes encoder / decoder to json.dump and json.load by using cls and object_hook. Therefore, passing args or kwargs to mongoengine_goodjson.Document.to_json / mongoengine_goodjson.Document.from_json, The arguments are put into json.dump and json.load.

Code Example

Here’s the example code what this section is saying. In this code, the document tries to serialize date into epoch time format (not ISO format).

import mongoengine as db
import mongoengine_goodjson as gj


class User(gj.Document):
  """User class."""
  name = db.StringField(required=True, unique=True)
  registered_date = db.DateTimeField()

  def to_json(self, *args, **kwargs):
    """Serialize into json."""
    return super(User, self).to_json(epoch_mode=True)

FAQ from issue tracker

Q: I’m using third-party package such as flask-mongoengine, but no ObjectId is replaced (#34)

A: Some third-party package has abstract classes that inherit classes from MongoEngine. To use mongoengine_goodjson with those packages, you will need to inherit the both of documents and queryset.

Example Code

Here is the example code to solve inheritance problem.

import mongoengine as db
import flask_mongoengine as fm
import mongoengine_goodjson as gj

class QuerySet(fm.BaseQuerySet, gj.QuerySet):
  """Queryset."""
  pass


class Document(db.Document, gj.Document):
  """Document."""
  meta = {
    'abstract': True,
    'queryset_class': QuerySet
  }


class User(Document):
  """User class."""
  name = db.StringField(required=True, unique=True)
  registered_date = db.DateTimeField()

Q: Is there a way to specify which format a DatetimeField will be resolved to? (#38)

A: Check Encoder / Decoder