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?
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:Now consider a document called
StackOverFlowUser
: this document is inherited from theUser
document and saves some StackOverflow-related information for 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:For a
StackOverFlowUser
object:If you are sure that a document is not going to have a sub-class document, then set
allow_inheritance
toFalse
and mongoengine will not save_cls
and_types
fields for that document.