Mongoose populate nested array

霸气de小男生 提交于 2019-11-28 05:27:48
Sven

Update: Please see Trinh Hoang Nhu's answer for a more compact version that was added in Mongoose 4. Summarized below:

Car
  .find()
  .populate({
    path: 'partIds',
    model: 'Part',
    populate: {
      path: 'otherIds',
      model: 'Other'
    }
  })

Mongoose 3 and below:

Car
  .find()
  .populate('partIds')
  .exec(function(err, docs) {
    if(err) return callback(err);
    Car.populate(docs, {
      path: 'partIds.otherIds',
      model: 'Other'
    },
    function(err, cars) {
      if(err) return callback(err);
      console.log(cars); // This object should now be populated accordingly.
    });
  });

For nested populations like this, you have to tell mongoose the Schema you want to populate from.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!