繁体   English   中英

找不到 id 并更新和增加子文档 - 返回 null Mongoose/mongoDB

[英]Cannot find id and update and increment sub-document - returns null Mongoose/mongoDB

我有一个问题,我似乎无法检索数组中嵌套对象的 _id。 特别是我的对象数组的食物部分。 我想找到 _id,比如说意大利烩饭,然后动态增加订单计数(来自同一个对象)。

我正在尝试动态完成此操作,因为我在 req.body._id 中尝试了 Risotto id,这很好,但我无法继续尝试增加订单,因为我得到了空值。

由于某种原因,我一直为空,我认为它是一个嵌套文档,但我不确定。 这也是我的路由文件和架构。

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
}

菜单名称的 id 可以代替它的位置,但我不需要它,因为我需要访问食物子文档。 提前致谢。

您正在向 MenuSchema.findByIdAndUpdate 更新查询发送食物 ID ( 5e3b75f2a3d43821a0fb57f0 )。 它应该是5e3b75f2a3d43821a0fb57ee的菜单 ID

您可以通过它的 id 找到菜单,并通过使用 food _id 或 foodname 使用mongodb $ positional operator更新它是其中一种食物。

通过提供菜单 id 和食物 id 进行更新:

router.patch("/update", [auth], async (req, res) => {
  try {
    const orderPlus = await MenuSchema.findByIdAndUpdate(
      "5e3b75f2a3d43821a0fb57ee",
      { $inc: { "foods.$[inner].orders": 1 } },
      { arrayFilters: [{ "inner._id": "5e3b75f2a3d43821a0fb57f0" }], new: true }
    );

    res.status(200).send(orderPlus);
  } catch (err) {
    res.status(500).send(err);
  }
});

通过提供菜单 ID 和食品名称进行更新:

router.patch("/update", [auth], async (req, res) => {
  try {
    const orderPlus = await MenuSchema.findByIdAndUpdate(
      "5e3b75f2a3d43821a0fb57ee",
      { $inc: { "foods.$[inner].orders": 1 } },
      { arrayFilters: [{ "inner.foodname": "Risotto" }], new: true }
    );

    res.status(200).send(orderPlus);
  } catch (err) {
    res.status(500).send(err);
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM