Search code examples
node.jsmongoosecoffeescriptpopulatemongoose-populate

Can you perform multiple nested populates in mongoose?


So, I'm building an app and it has a Restaurant model, the restaurants have reviews. The reviews have a user which I am populating like this(coffeescript):

exports.listOne = (req, res) ->
  Restuarant.findOne 
    _id: req.params.id
  .populate({ path: 'reviews' })
  .exec (err, docs) ->
    options = 
      path: 'reviews.userId'
      model: 'User'
    if err
      return res.json(500)
    Venue.populate docs, options, (err, venues) ->
      res.json venues
      return
    return

The problem is Users have a reference to a Hotel model which I also want to populate, is it possible for me to populate hotels within this query?


Solution

  • Mongoose now supports deep population which should solve your problem. You should be able to pass something like this to your populate (hard to say exactly without seeing the models):

    .populate({
        path: 'reviews',
        model: 'Review',
        populate: {
          path: 'user',
          model: 'User',
          populate: {
            path: 'hotel',
            model: 'Hotel'
          }
        }
      })...
    

    Here's a nice article on population that may help: http://frontendcollisionblog.com/mongodb/2016/01/24/mongoose-populate.html