Search code examples
databasemongodbmongoosemongoose-schemamongoose-populate

Mongoose: Multiple Populate on nested level


I think code example will much better than English explanation of problem.

Car
.find()
.populate({
  path: 'partIds',
  model: 'Part',
  populate: {            // First Populate
    path: 'otherIds',
    model: 'Other'
  }
  populate: {            // Second Populate
    path: 'ModelIds',
    model: 'Model'
  }
})

So, basically, I want to do double populate in one nested level. While Mongoose 4.5 support something like below.

Car
 .find()
 .populate({ 
   path: 'partIds',
   model: 'part',
   populate: {            // Only single nested populate
     path: 'otherIds',
     model: 'Other'
   }
})

Please tell me, how can we do that? Any kind of help will be greatly appreciated.


Solution

  • You can use array in populate for multiple fields.

    Car
    .find()
    .populate({
      path: 'partIds',
      model: 'Part',
      populate: [{            // First Populate
        path: 'otherIds',
        model: 'Other'
      },
      {                      // Second Populate
        path: 'ModelIds',
        model: 'Model'
      }]
    })