mongoose填充嵌套数组
假设以下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一样的库为每个进行填充调用,并等到所有完成,然后返回。
可能没有循环所有的汽车?
更新:请参阅Trinh Hoang Nhu的答案 ,在Mongoose 4中添加了更加紧凑的版本。总结如下:
Car .find() .populate({ path: 'partIds', model: 'Part', populate: { path: 'otherIds', model: 'Other' } })
mongoose3及以下:
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。
mongoose4支持这个
Car .find() .populate({ path: 'partIds', model: 'Part', populate: { path: 'otherIds', model: 'Other' } })
使用mongoosedeepPopulate插件
car.find().deepPopulate('partIds.otherIds').exec();