数组发送到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会导致对象中的数组为空
发布评论