假设有以下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 回答
Update: 请参阅Trinh Hoang Nhu's answer以获取在Mongoose 4中添加的更紧凑的版本 . 总结如下:
Mongoose 3 and below:
对于像这样的嵌套群体,您必须告诉mongoose您想要填充的Schema .
猫鼬4支持这一点
使用mongoose deepPopulate plugin