首页 文章

Mongoose填充嵌套数组

提问于
浏览
17

假设有以下3种型号:

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

var PartSchema = new Schema({
  name: {type: String},
  otherIds: [{type: Schema.Types.ObjectId, ref: 'Other'}],
});

var OtherSchema = new Schema({
  name: {type: String}
});

当我查询汽车时,我可以填充零件:

Car.find().populate('partIds').exec(function(err, cars) {
  // list of cars with partIds populated
});

有没有办法在mongoose中填充所有汽车的嵌套零件对象中的otherIds .

Car.find().populate('partIds').exec(function(err, cars) {
  // list of cars with partIds populated
  // Try an populate nested
  Part.populate(cars, {path: 'partIds.otherIds'}, function(err, cars) {
    // This does not populate all the otherIds within each part for each car
  });
});

我可以迭代每辆车并尝试填充:

Car.find().populate('partIds').exec(function(err, cars) {
  // list of cars with partIds populated

  // Iterate all cars
  cars.forEach(function(car) {
     Part.populate(car, {path: 'partIds.otherIds'}, function(err, cars) {
       // This does not populate all the otherIds within each part for each car
     });
  });
});

问题是我必须使用像async之类的lib来为每个执行填充调用,并等待所有操作完成然后返回 .

没有循环所有汽车可能吗?

3 回答

  • 32

    Update: 请参阅Trinh Hoang Nhu's answer以获取在Mongoose 4中添加的更紧凑的版本 . 总结如下:

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

    对于像这样的嵌套群体,您必须告诉mongoose您想要填充的Schema .

  • 22

    猫鼬4支持这一点

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

    使用mongoose deepPopulate plugin

    car.find().deepPopulate('partIds.otherIds').exec();
    

相关问题