【问题标题】:Cannot find id and update and increment sub-document - returns null Mongoose/mongoDB找不到 id 并更新和增加子文档 - 返回 null Mongoose/mongoDB
【发布时间】: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


    【解决方案1】:

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

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

    通过提供菜单 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);
      }
    });
    

    【讨论】:

    • 您先生是个天才!这完美无缺。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 2019-08-18
    • 2016-07-30
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    • 2016-03-12
    相关资源
    最近更新 更多