首页 > 解决方案 > 无法填充嵌套数组

问题描述

我知道这已经被问了一百万次,但它似乎对我不起作用。从数据库中获取对象时,我找不到一种方法来填充对象中的引用。无论我尝试什么,它要么返回一个空列表,要么只返回 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"
    }]
});

标签: javascriptnode.jsmongoose

解决方案


参考您的架构,看起来您只需要这样做:

Merchant.find({cloverId: merchantId}).populate("ingredients.ingredient")...

推荐阅读