node.js - 将对象中的数据数组发送到 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');
试试这个
推荐阅读
- flutter - 未处理的异常:在 null 上调用了 getter 'name'
- javascript - 有没有办法使用 cypress/JS 以编程方式通过 Keycloak 登录应用程序?
- javascript - 使脚本仅适用于特定的屏幕尺寸
- python - 有没有办法将列表返回为句子格式python
- javascript - 当我在字段集中取消隐藏和重新隐藏图例标签时出现问题
- php - MySQL 和 PHP - 在一列中按多个条件进行过滤
- python - 代码:Python,错误类型:“int”对象不可下标
- c# - 将此作为继承类型返回
- html - HTML CSS 导航栏问题
- wordpress - 错误显示在 DB 中未找到锁定条目