首页 > 解决方案 > 将对象中的数据数组发送到 API 会导致对象中的数组为空

问题描述

我有一个 API 来制作鸡尾酒。每款鸡尾酒都有一份配料表。在鸡尾酒模式中,我想添加如下(成分)

鸡尾酒模式

const schema = new Schema({
    name: { type: String, required: true },
    recipe: {type: String, required: true },
    ingredients: [{
        ingredient: {type: mongoose.Schema.Types.ObjectId, ref: 'Ingredient'}
        quantity: {type: Number, required: false},
        quantityType: {type: String, required: false}
    }],
    creator: {
        type: mongoose.Schema.Types.ObjectId,
        ref:'User'
    },
    createdDate: { type: Date, default: Date.now }
});

我填充鸡尾酒如下

return await Cocktail.find()
    .populate('ingredients', 'name alcoholic')
    .populate('creator', 'username')
    .select('name recipe ingredients creator');

创建鸡尾酒时,我将其作为请求的主体。我使用邮递员来做到这一点。

{
    "name": "Cooled Vodka",
    "recipe": "Vodka and Ice, what's there to do wrong?",
    "ingredients": [
        {
            "ingredient": "5eb8611ebf0d4b0017bf0d47",
            "quantity": "4",
            "quantityType": "pcs"
        },
        {
            "ingredient": "5eb86186bf0d4b0017bf0d48",
            "quantity": "4",
            "quantityType": "cl"
        }
    ],
    "creator": "5eb85eb0bf0d4b0017bf0d46"
}

其中两个成分和创建者标签分别是成分和用户的有效 ID。发送请求会给出 200 OK 状态,但是当从我的数据库中取出所有鸡尾酒时,这就是结果。成分字段的空数组

[
    {
        "_id": "5eb863b4bf0d4b0017bf0d4b",
        "name": "Cooled Vodka",
        "recipe": "Vodka and Ice, what's there to do wrong?",
        "ingredients": [],
        "creator": {
            "_id": "5eb85eb0bf0d4b0017bf0d46",
            "username": "Bartender",
            "id": "5eb85eb0bf0d4b0017bf0d46"
        },
        "id": "5eb863b4bf0d4b0017bf0d4b"
    }
]

我不知道我哪里错了。

标签: node.jsmongodbapimongoosepostman

解决方案


return await Cocktail.find()
    .populate('ingredients.ingredient', 'name alcoholic')
    .populate('creator', 'username')
    .select('name recipe ingredients creator');

试试这个


推荐阅读