los*_*ion 18 mongoose mongodb node.js 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}
});
Run Code Online (Sandbox Code Playgroud)
当我查询汽车时,我可以填充零件:
Car.find().populate('partIds').exec(function(err, cars) {
// list of cars with partIds populated
});
Run Code Online (Sandbox Code Playgroud)
有没有办法在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
});
});
Run Code Online (Sandbox Code Playgroud)
我可以迭代每辆车并尝试填充:
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
});
});
});
Run Code Online (Sandbox Code Playgroud)
问题是我必须使用像async之类的lib来为每个执行填充调用,并等待所有操作完成然后返回.
没有循环所有汽车可能吗?
Sve*_*ven 33
更新:请参阅Trinh Hoang Nhu关于Mongoose 4中添加的更紧凑版本的答案.总结如下:
Car
.find()
.populate({
path: 'partIds',
model: 'Part',
populate: {
path: 'otherIds',
model: 'Other'
}
})
Run Code Online (Sandbox Code Playgroud)
猫鼬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.
});
});
Run Code Online (Sandbox Code Playgroud)
对于像这样的嵌套群体,您必须告诉mongoose您想要填充的Schema.
Tri*_*Nhu 23
猫鼬4支持这一点
Car
.find()
.populate({
path: 'partIds',
model: 'Part',
populate: {
path: 'otherIds',
model: 'Other'
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22408 次 |
| 最近记录: |