javascript - 无法填充嵌套数组
问题描述
我知道这已经被问了一百万次,但它似乎对我不起作用。从数据库中获取对象时,我找不到一种方法来填充对象中的引用。无论我尝试什么,它要么返回一个空列表,要么只返回 id 列表。我在这里做错了什么?
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")...
推荐阅读
- c++ - 什么是在 C++ 中调用的具有类类型的函数?
- javascript - Angular 2 - 创建指令
- javascript - doPost() 可以自己运行吗?
- php - Laravel 背包权限播种“角色不存在”
- java - REST-assured 3.0.0 和 Java 11 的 java.lang.NoClassDefFoundError(Java 8 未观察到)
- javascript - 视频大小和 WebRTC 的问题
- python - 从表中垂直读取抓取的数据,而不是水平读取 Python
- image-processing - 使用 graphicsmagick 裁剪可变宽度框架
- node.js - 从多个视频文件到单个输出
- sql - 如何选择与列表中所有值匹配的值?