问题描述
假设以下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}
});
查询汽车时,我可以填充零件:
When I query for Cars I can populate the parts:
Car.find().populate('partIds').exec(function(err, cars) {
// list of cars with partIds populated
});
猫鼬是否有办法在所有汽车的嵌套零件对象中填充otherIds.
Is there a way in mongoose to populate the otherIds in the nested parts objects for all the cars.
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
});
});
我可能可以遍历每辆车并尝试填充:
I can probably iterate over each car and try to populate:
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之类的库来对每个对象进行填充调用,然后等到所有操作完成后再返回.
Problem there is that I have to use a lib like async to make the populate call for each and wait until all are done and then return.
有可能不循环所有汽车吗?
Possible to do without looping over all cars?
推荐答案
更新:请参阅 Trinh Hoang Nhu的答案是Mongoose 4中添加的更紧凑的版本.总结如下:
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'
}
})
猫鼬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.
});
});
对于这样的嵌套种群,您必须告诉猫鼬您想从中填充的模式.
For nested populations like this, you have to tell mongoose the Schema you want to populate from.
这篇关于猫鼬填充嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!