Mongoose populate nested array

前端 未结 1 828
刺人心
刺人心 2020-12-02 18:49

Assuming the following 3 models:

var CarSchema = new Schema({
  name: {type: String},
  partIds: [{type: Schema.Types.ObjectId, ref: \'Part\'}],
});

var Par         


        
相关标签:
1条回答
  • 2020-12-02 19:36

    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.

    0 讨论(0)
提交回复
热议问题