将对象中的数据数组发送到API会导致对象中的数组为空

编程入门 行业动态 更新时间:2024-10-08 18:40:46

将对象中的数据<a href=https://www.elefans.com/category/jswz/34/1771288.html style=数组发送到API会导致对象中的数组为空"/>

将对象中的数据数组发送到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"
    }
]

我不知道哪里出问题了。

回答如下:
return await Cocktail.find()
    .populate('ingredients.ingredient', 'name alcoholic')
    .populate('creator', 'username')
    .select('name recipe ingredients creator');

尝试这个

更多推荐

将对象中的数据数组发送到API会导致对象中的数组为空

本文发布于:2024-05-07 14:05:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1756597.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   象中   将对   发送到   为空

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!