【发布时间】:2020-05-24 08:37:26
【问题描述】:
我有一个问题,我似乎无法检索数组中嵌套对象的 _id。特别是我的对象数组的食物部分。我想找到_id,比如说烩饭,然后动态增加订单数(来自同一个对象)。
我正在尝试动态完成这项工作,因为我已经尝试了 req.body._id 中的 Risotto id,这很好,但是当我得到 null 时,我无法继续尝试增加订单。
由于某种原因,我一直为 null,我认为它是一个嵌套文档,但我不确定。这也是我的路由文件和架构。
router.patch("/update", [auth], async (req, res) => {
const orderPlus = await MenuSchema.findByIdAndUpdate({ _id: '5e3b75f2a3d43821a0fb57f0' }, { $inc: { "food.0.orders": 1 }}, {new: true} );
//want to increment orders dynamically once id is found
//not sure how as its in its own seperate index in an array object
try {
res.status(200).send(orderPlus);
} catch (err) {
res.status(500).send(err);
}
});
架构:
const FoodSchema = new Schema({
foodname: String,
orders: Number,
});
const MenuSchema = new Schema({
menuname: String,
menu_register: Number,
foods: [FoodSchema]
});
这是返回的数据库 JSON
{
"_id": "5e3b75f2a3d43821a0fb57ee",
"menuname": "main course",
"menu_register": 49,
"foods": [
{
"_id": "5e3b75f2a3d43821a0fb57f0",
"foodname": "Risotto",
"orders": 37
},
{
"_id": "5e3b75f2a3d43821a0fb57ef",
"foodname": "Tiramisu",
"orders": 11
}
],
"__v": 0
}
menuname 的 id 可以代替它,但我不需要它,因为我需要访问 food 子文档。提前致谢。
【问题讨论】:
标签: node.js mongodb express mongoose increment