¡Esta es una revisión vieja del documento!
It's a MongoDB ORM for Python.
$ pip install mongoengine
To start using MongoEngine we will import like this:
import mongoengine
To connect a DB we will use the connect function, its first argument is the DB:
connect('project1') connect('project1', host='192.168.1.35', port=12345) connect('project1', username='webapp', password='pwd123') connect('project1', host='mongodb://localhost/database_name')
Next schema implements a Blog where a User can create different type Posts. Those types are inherited classes from Post.
class User(Document): email = StringField(required=True) first_name = StringField(max_length=50) last_name = StringField(max_length=50) class Post(Document): title = StringField(max_length=120, required=True) author = ReferenceField(User) meta = {'allow_inheritance': True} class TextPost(Post): content = StringField() class ImagePost(Post): image_path = StringField() class LinkPost(Post): link_url = StringField()
tags = ListField(StringField(max_length=30)), a ListField is a field object that allows to have a list of other field objects (including other lists).class Comment(EmbeddedDocument): content = StringField() name = StringField(max_length=120) class Post(Document): title = StringField(max_length=120, required=True) author = ReferenceField(User) tags = ListField(StringField(max_length=30)) comments = ListField(EmbeddedDocumentField(Comment))
When we define a ReferenceField we can indicate reverse_delete_rule=CASCADE to delete all the objects when a referenced object is deleted (it does not work with MapFields neither DictFields).
class Post(Document): title = StringField(max_length=120, required=True) author = ReferenceField(User, reverse_delete_rule=CASCADE) tags = ListField(StringField(max_length=30)) comments = ListField(EmbeddedDocumentField(Comment))