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>"
}
}
]
}
https://stackoverflow.com/questions/65714210/
相关文章:
android - 如何在没有任何延迟的情况下在android中循环播放音频文件?
python - python 中的 turtle 迷宫。我不知道如何避免 turtle 穿墙和作弊
css - 如何将我的 mat-table CSS 列宽设置为只占用与数据一样多的空间?
tensorflow - 用 bazel 构建 tensorflow 不会产生静态库文件?
javascript - (Javascript) 判断对象数组中是否包含一个numbervalue
javascript - react : onChange callback not firing
php - 将动态值插入特定 WooCommerce 电子邮件模板的文本字符串中