【问题标题】:sending array of data in object to API results in empty array in object将对象中的数据数组发送到 API 会导致对象中的数组为空
【发布时间】:2020-08-29 21:37:58
【问题描述】:

我有一个用于制作鸡尾酒的 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');

在创建鸡尾酒时,我将其作为请求的主体。我使用 Postman 来执行此操作。

{
    "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.js mongodb api mongoose postman


    【解决方案1】:
    return await Cocktail.find()
        .populate('ingredients.ingredient', 'name alcoholic')
        .populate('creator', 'username')
        .select('name recipe ingredients creator');
    

    试试这个

    【讨论】:

    • 谢谢!那行得通。一个简单的解决方案,但我自己找不到
    • 没问题兄弟..!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 2021-10-25
    • 2019-08-24
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    相关资源
    最近更新 更多