首页 > 解决方案 > 通过 ID 更新 Mongoose 中的数组元素

问题描述

我想修改单个 MongoDB 文档中的数组元素,但我不知道如何。这是我拥有的示例文档。

{
    "_id": "5eefbb77dcc4af0255ef52c6",
    "question": "How are you?",
    "answers": [
      {
        "count": 5,
        "_id": "5eefbb77dcc4af0255ef52c7",
        "body": "Fantastic"
      },
      {
        "count": 20, // I want to increment this by 1
        "_id": "5eefbb77dcc4af0255ef52c8",
        "body": "Meh"
      },
      {
        "count": 100,
        "_id": "5eefbb77dcc4af0255ef52c9",
        "body": "Bad"
      }
    ],
    "createdAt": "2020-06-21T19:56:39.336Z",
    "updatedAt": "2020-06-21T19:56:39.336Z",
    "__v": 0
  },

我目前正在尝试使用 document.FindByIdAndUpdate(),但我不知道如何使用。任何帮助表示赞赏!

标签: mongodbmongoose

解决方案


这对你来说应该很好:

    Model.findOneAndUpdate({ _id: "5eefbb77dcc4af0255ef52c6", "answers._id": "5eefbb77dcc4af0255ef52c8" }, 
     { $inc: { "answers.$.count": 1 }, 
     { new: true } 
    })
    .then((item) => {
       console.log(item)
    }, (e) => {
       console.log(e)
    })

上面的查询将找到确切的答案,然后将计数加 1。


推荐阅读