MongoEngine _types and _cls fields

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

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?

回答1:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!