Specifying collection name with MongoEngine

落爺英雄遲暮 提交于 2020-01-13 08:43:27

问题


Once content is added the name of the collection is defaulted to the name of the class. Is it possible to specify the collection name or is my approach wrong? Using the code I have my collection is then named "mongo_engine_python" by default.

from mongoengine import *

try:
    connect(
        db='MongoEngine_Test',
        host="mongodb://localhost:27017/"
    )
    print("Connection successful")
except:
    print("Unable to connnect") 

class MongoEnginePython(Document):
    item_name = StringField(max_length=200, required=True)
    item_price = IntField(default=0)

回答1:


Didn't look at the docs properly. Here it is:

2.3.4. Document collections

Document classes that inherit directly from Document will have their own collection in the database. The name of the collection is by default the name of the class, converted to lowercase (so in the example above, the collection would be called page). If you need to change the name of the collection (e.g. to use MongoEngine with an existing database), then create a class dictionary attribute called meta on your document, and set collection to the name of the collection that you want your document class to use:

class Page(Document):
    title = StringField(max_length=200, required=True)
    meta = {'collection': 'cmsPage'}


来源:https://stackoverflow.com/questions/53976963/specifying-collection-name-with-mongoengine

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