python - 填充在 Mongoengine 中,引用字段

标签 python mongodb mongoengine

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/

相关文章:

python - 从/sdb1读取数据

javascript - 服务器上的正确变量通过 socket.io 作为错误变量传递给客户端

ruby-on-rails - rails 3 : Migrate DB Schema from SQLite to MongoDB

python - mongoengine 默认超时配置

python - PIL/Pillow 将图像转换为列表并再次返回

python线程事件: why do we need clear()

python - 如何在 Cython 中获得内存 View 列表?

MongoDB:在子文档中查找带有键的文档

python - 在mongoengine中获取动态集合名称

Django1.8和Mongoclient settings.DATABASES配置不正确。