3

Is it possible to simultaneously populate multiple paths using mongoose? I am trying to do something like this:

User.findById(_id)
  .populate({
    path:'friendIds',
    model:'User',
    populate: {
      path: 'reviewIds',
      model: 'Review',
      populate: [{
        path: 'userId',
        model: 'User'
      }, {
        path: 'locationId',
        model: 'Location'
      }]
    }
  })

Where the User has friends who are Users, who have written Reviews, which have an author (User) and a Location. I'm trying to deep populate all of that info. Above is my most recent attempt, and it doesn't work. Is there a way to do this?

Just as a reference, if I don't want multiple paths populated, it works fine like this:

User.findById(_id)
  .populate({
    path:'friendIds',
    model:'User',
    populate: {
      path: 'reviewIds',
      model: 'Review',
      populate: {
        path: 'locationId',
        model: 'Location'
      }
    }
  })

But then my reviews don't have the User populated on them.

Read more about deep populate in the mongoose docs.

devigner
  • 152
  • 12

1 Answers1

2

Yes, it does work. I've used it many times. Here's an example:

Model.find()
.populate({
    path: 'replies',
    populate: [{
      path: 'user',
      select: 'displayName username'
    }, {
      path: 'replies',
      populate: {
        path: 'user',
        select: 'displayName username'
      }
    }]
}).exec(...
tutley
  • 446
  • 3
  • 9