Quick note: when defining __init__ function for a MongoEngine’ *Document, do not forget to call parent constructor. Example:
from mongoengine import * class MyDocument(Document): def __init__(self): Document.__init__(self) [...]
Quick note: when defining __init__ function for a MongoEngine’ *Document, do not forget to call parent constructor. Example:
from mongoengine import * class MyDocument(Document): def __init__(self): Document.__init__(self) [...]
I have recently tested Django with MongoDB, using MongoEngine to connect Django to MongoDB.
I often use some attributes common to multiple models and I do not like to copy-paste, so I always use class inheritance. This is particularly true with ORM (such as doctrine within Symfony 2 PHP Framework).
For example, my “base document” looks like (no syntax at all)
class BaseDocument - attribute 1 - attribute 2 - attribute 3
and derived documents look like
class Derived1 derived from BaseDocument [...]
With MongoEngine, your models derived from “Document”. For example:
from mongoengine import * class BaseDocument(Document): title = StringField() content = StringField()
If you want to derived from BaseDocument, there are 2 approaches:
class Derived1(BaseDocument): author = StringField()
you’ll get an error. MongoEngine Document is not extended properly.
So far, the best way I have found is :
# Here, BaseDocument is a 'raw' class class BaseDocument(): title = StringField() content = StringField() # the targeted class inherits from MongoEngine's Document and our BaseDocument class Derived1(Document, BaseDocument): author = StringField() def __init__(self): Document.__init__(self) BaseDocument.__init__(self)
And no more error at all and working properly as expected.