将对象中的数据数组发送到API会导致对象中的数组为空 [英] sending array of data in object to API results in empty array in object

查看:147
本文介绍了将对象中的数据数组发送到API会导致对象中的数组为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于创建鸡尾酒的API。每个鸡尾酒都有一个成分清单。在鸡尾酒配方中,我想添加以下内容(成分)

I have an API to create cocktails. Each cocktail has a list of Ingredients. In the cocktailschema I want to add this as following (ingredients)

鸡尾酒配方

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 }
});

我按如下方式填充鸡尾酒

I populate the cocktails as follows

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

创建鸡尾酒时,请将其作为请求的正文。我用邮递员来做。

When creating a Cocktail I give this as the body of my request. I use Postman to do this.

{
    "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状态,但是当从我的数据库中取出所有鸡尾酒时,这就是结果。成分字段的空数组

where the two ingredient and the creator tags are valid IDs for respectively ingredients and a user. Sending the request gives a 200 OK status however when getting all the cocktails out of my db, this is the result. An empty array for the ingredients field

[
    {
        "_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会导致对象中的数组为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆