mongoengine有没有类似的填充方法
db.collection.posts.findById(id).populate('user_id')
最佳答案
一天过去了,但我仍然没有看到 mongoengine
中有与 .populate()
相关的 API 文档,我选择了自己的方式.
mongoengine
是一个 Object-Oriented驱动程序,与 mongoose
相比,已经有预定义函数 .populate()
但如果您知道 OOP 的工作原理,这对您来说只是小菜一碟,这里有一个简单的技巧
# .schema.author.py
class Author(Document):
name = StringField(required=True)
# .schema.book.py
class Book(Document):
title = StringField()
author = ReferenceField(Author)
def tojson(self):
json = {
'title ': self.title ,
'author ': self.author,
}
json['author'] = self.author.name
return json
# .route.book.py
def get(self):
try:
books = []
for book in Book.objects:
books.push(book.tojson())
return {'status': True, 'response': books}
except Exception as e:
print(e)
并且必须为每个 Book
对象填充预期结果 Author
{
"status": true,
"response": [
{
"title": "<book-name>",
"author": {
"name": "<author-name>"
}
}
]
}
关于python - 填充在 Mongoengine 中,引用字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65714210/