Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoEngine _types and _cls fields

Why does mongoengine add _types and _cls fields to every document of a collection.
Both of them are a (key, value) pair and both of them contain the name of the document's model class. The only difference is _types value is a list and I assume it can have multiple model class names if there is involved some inheritance.

However the question is: why do I need them to exist in every document within a collection when all the documents will have the same values for both fields?

like image 906
Traian Avatar asked Dec 11 '12 16:12

Traian


1 Answers

Mongoengine allows Document Inheritance. When defining a class a meta attribute allow_inheritance is used to allow subclassing this particular class. The _cls and _types fields are used to identify which class the object belongs to.

Consider a document called User used to store users' information:

class User(Document):
    meta = {'allow_inheritance': True}
    # stores information regarding a user

Now consider a document called StackOverFlowUser : this document is inherited from the User document and saves some StackOverflow-related information for a user:

class StackOverFlowUser(User):
    # stores StackOverflow information of a user

For both these document classes, mongoengine will use the same collection named user. No matter which document object you create, it will be stored as a document in this collection.

To differentiate to which class the object belongs to, _cls and _types fields will be used.

For a User object:

{
    ...
    '_cls' = 'User',
    '_types' = ['User', 'User.StackOverFlowUser']
}

For a StackOverFlowUser object:

{
    ...
    '_cls' = 'User.StackOverFlowUser',
    '_types' = ['User', 'User.StackOverFlowUser']
}

If you are sure that a document is not going to have a sub-class document, then set allow_inheritance to False and mongoengine will not save _cls and _types fields for that document.

like image 129
Crazyshezy Avatar answered Oct 13 '22 02:10

Crazyshezy