Javascript 无法填充嵌套数组
我知道这个问题已经被问过无数次了,但它似乎对我不起作用。从数据库获取对象时,我找不到填充对象中引用的方法。无论我尝试什么,它要么返回一个空列表,要么只返回id列表。我做错了什么Javascript 无法填充嵌套数组,javascript,node.js,mongoose,Javascript,Node.js,Mongoose,我知道这个问题已经被问过无数次了,但它似乎对我不起作用。从数据库获取对象时,我找不到填充对象中引用的方法。无论我尝试什么,它要么返回一个空列表,要么只返回id列表。我做错了什么 displayInventory: (req, res)=>{ Merchant.find({otherId: merchantId}) .populate({ path: "ingredients", populate: {
displayInventory: (req, res)=>{
Merchant.find({otherId: merchantId})
.populate({
path: "ingredients",
populate: {
path: "ingredient",
model: "Ingredient"
}
})
.then((merchant)=>{
console.log(merchant);
if(merchant){
return res.render("./inventory/inventory", {merchant: merchant});
}else{
return res.redirect("/merchant/new");
}
})
.catch((err)=>{
console.log(err);
return res.render("error");
});
}
const MerchantSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
otherId: {
type: String,
required: true
},
lastUpdatedTime: {
type: Date,
default: Date.now
},
ingredients: [{
ingredient: {
type: mongoose.Schema.Types.ObjectId,
ref: "Ingredient"
},
quantity: {
type: Number,
min: [0, "Quantity cannot be less than 0"]
}
}],
recipes: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Recipe"
}]
});
参考您的模式,看起来您只需要执行以下操作:
Merchant.find({cloverId: merchantId}).populate("ingredients.ingredient")...
您可以尝试下面的代码
Merchant.find({otherId: merchantId})
.populate({ path: 'ingredients' })
.exec(function(err, docs) {
var options = {
path: 'ingredients.components',
model: 'Ingredient'
};
if (err) return res.json(500);
Merchant.populate(docs, options, function (err, merchant) {
res.json(merchant);
});
});
我会回答我自己的问题,以防其他人有类似的问题。我的问题是,我重命名了一些变量,但在将数据保存到数据库时忘记了这样做。愚蠢的错误,但只是提醒重构时要小心。我使用了Congu Le Ngoc的答案,它工作得非常完美。当我这样做时,它只会给我实际的id,比如:库存:[{u id:5d97508e7929f31fb64a3196,数量:123},…什么是库存?我在您的模式中没有看到它。库存是正在呈现的ejs页面。但是,我解决了我的问题。重构并弄乱了数据库中的一些东西。解决了它,这种填充方式工作得很好。谢谢。当我添加此内容时,我只是得到一个关于未定义项目的错误。我不知道真的明白这段代码在做什么,所以我不知道如何编辑它为我的需要。。。