gpt4 book ai didi

node.js - Mongoose 填充嵌套数组

转载 作者:IT老高 更新时间:2023-10-28 13:06:31 26 4
gpt4 key购买 nike

假设以下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}
});

当我查询 Cars 时,我可以填充零件:

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's answer用于在 Mongoose 4 中添加的更紧凑的版本。总结如下:

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

Mongoose 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。

关于node.js - Mongoose 填充嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28179720/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com