Populate in Mongoengine, Reference Field

Viewed 438

Does mongoengine have a similar method to populate

db.collection.posts.findById(id).populate('user_id')
2 Answers

day goes by but still I didn't saw anything that there is an API documentation related to .populate() in mongoengine and I chose to make my own way.

mongoengine is an Object-Oriented driver, compare to mongoose there is already predefined function .populate() but if you know how OOP works it is just a piece of cake for you, here is a simple trick

# .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)
  

and the expected result must be populated Author for each Book object

{
  "status": true,
  "response": [
     {
         "title": "<book-name>",
         "author": {
            "name": "<author-name>"
         }
     }
  ]
}

I am not an expert in MongoEngine, but you can query like this:

post = Posts.objects(id=id).first()

That returns the data from that Model and it's already populated. You can access the author of the post using:

post.author.name

Related