jmona789 jmona789 - 1 year ago 101
Node.js Question

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

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?

Answer Source

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):

    path: 'reviews',
    model: 'Review',
    populate: {
      path: 'user',
      model: 'User',
      populate: {
        path: 'hotel',
        model: 'Hotel'

Here's a nice article on population that may help:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download