我在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'