Search code examples
mongoosemean-stackmongoose-populate

Mongoose populate - when


I want to populate posts with author name. I created models with references, routes also. When should I populate posts, before saving new post or later, how does it work actually ?


Solution

  • Population is used when querying to replace a stored id in one document with the corresponding document from another collection.

    You will need to save the _id of the author document in your post documents:

    var post = new Post({
      ...
      author: // id of author doc
      ...
    })
    
    post.save()
    

    You would then use populate when retrieving the documents in order to replace the stored author id with the author document itself:

    Post
      .find({})
      .populate('author')
      .exec(function (err, posts) {
        if (err) {
          // Handle error
        }
    
        // Handle results
        posts.forEach(post => {
          // Assuming author documents have a 'name' property
          console.log(post.author.name)
        })
      })
    

    This might also help: http://mongoosejs.com/docs/populate.html