Mongoose填充嵌套数组

时间:2015-01-27 20:49:14

标签: node.js mongodb mongoose mongoose-populate

假设有以下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来为每个执行填充调用,并等待所有操作完成然后返回。

可以不绕过所有汽车吗?

4 个答案:

答案 0 :(得分:32)

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

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

猫鼬3及以下:

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。

答案 1 :(得分:22)

Mongoose 4支持此

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

答案 2 :(得分:4)

使用mongoose deepPopulate plugin

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

答案 3 :(得分:0)

最好搭配

Car
.find()
.populate({
    path: 'partIds.othersId'
})