将一个id_字段添加到MongoDb中的Document - Python

时间:2015-10-27 20:41:21

标签: python mongodb

我在Python中使用mongoengine库,以便动态地将集合添加到我的mongodb实例中。

所以我按如下方式定义了一个类Page

from mongoengine import *

class Comment(EmbeddedDocument):
   content = StringField()

class Author(EmbeddedDocument):
   # I only need the id_ field for this embedded document.
   pass

class Page(DynamicDocument):
   title = StringField(max_length=200, required=True)
   date_modified = DateTimeField(default=datetime.datetime.now)
   tags=['mongodb', 'mongoengine']
   comments = ListField(EmbeddedDocumentField(Comment))

comment1 = Comment(content="Good Work!")
comment2 = Comment(content="Nice Article")

page = Page(title="Using MongoEngine", comments=[comment1, comment2])
author = Author()
page.author = author
page.save()

一切都好。当我查看mongodb条目时,我看到:

> db.page.findOne()
{
    "_id" : ObjectId("562fe1372ea1864ac47db300"),
    "title" : "Using MongoEngine",
    "date_modified" : ISODate("2015-10-27T13:40:23.135Z"),
    "comments" : [
        {
            "content" : "Good work!"
        },
        {
            "content" : "Nice article!"
        }
    ],
    "author" : {
        "_cls" : "Author"
    }
}

就是这样,id_中缺少author字段。我该如何解决这个问题?

*****更新****

If I add `author.save()` I will get:
Traceback (most recent call last):
  File "/home/ubuntu/test.py", line 24, in <module>
    author.save()
  File "/Library/Python/2.7/site-packages/mongoengine/document.py", line 84, in save
    self._instance.save(*args, **kwargs)
AttributeError: 'NoneType' object has no attribute 'save'

0 个答案:

没有答案