首页 > 解决方案 > 猫鼬在NodeJS中的数组数组中更新值

问题描述

我的测试架构:

var TestSchema = new Schema({
    testName: String,
    topic: {
        topicTitle: String,
        topicQuestion: [
            {
                questionTitle: String,
                choice: [
                    {
                        name: String
                        age: Number
                    }
                ]
            }
        ]
    }
}, { collection: 'test' });
var Test = mongoose.model('test', TestSchema);

我想更新一个我有选择 ID 的年龄($inc) 值。

我可以有test idtopicQuestion idchoice id

如何在 NodeJS 中用猫鼬编写这个查询?

通常我使用下面的查询来更新一个值:

Test.findOneAndUpdate({ _id: testId }, { $inc: { ... } }, function (err, response) {
   ...
});

但是很难进入阵列和另一个阵列。谢谢

标签: node.jsmongodbmongoosemongoose-schema

解决方案


您可以使用$[] 位置运算符来更新嵌套数组。

router.put("/tests/:testId/:topicQuestionId/:choiceId", async (req, res) => {
  const { testId, topicQuestionId, choiceId } = req.params;

  const result = await Test.findByIdAndUpdate(
    testId,
    {
      $inc: {
        "topic.topicQuestion.$[i].choice.$[j].age": 1
      }
    },
    {
      arrayFilters: [{ "i._id": topicQuestionId }, { "j._id": choiceId }],
      new: true
    }
  );
  res.send(result);
});

假设我们有这个现有的文档:

{
    "_id" : ObjectId("5e53e7d9bf65ac4f5cbf2116"),
    "testName" : "Test 1",
    "topic" : {
        "topicTitle" : "Title",
        "topicQuestion" : [
            {
                "_id" : ObjectId("5e53e7d9bf65ac4f5cbf211a"),
                "questionTitle" : "Question 1 Title",
                "choice" : [
                    {
                        "_id" : ObjectId("5e53e7d9bf65ac4f5cbf211c"),
                        "name" : "A",
                        "age" : 1
                    },
                    {
                        "_id" : ObjectId("5e53e7d9bf65ac4f5cbf211b"),
                        "name" : "B",
                        "age" : 2
                    }
                ]
            },
            {
                "_id" : ObjectId("5e53e7d9bf65ac4f5cbf2117"),
                "questionTitle" : "Question 2 Title",
                "choice" : [
                    {
                        "_id" : ObjectId("5e53e7d9bf65ac4f5cbf2119"),
                        "name" : "C",
                        "age" : 3
                    },
                    {
                        "_id" : ObjectId("5e53e7d9bf65ac4f5cbf2118"),
                        "name" : "D",
                        "age" : 4
                    }
                ]
            }
        ]
    },
    "__v" : 0
}

如果我们想增加给定选择的值,我们使用这样的端点age发送请求 ,其中PUThttp://.../tests/5e53e7d9bf65ac4f5cbf2116/5e53e7d9bf65ac4f5cbf211a/5e53e7d9bf65ac4f5cbf211b

"testId": "5e53e7d9bf65ac4f5cbf2116"

"topicQuestionId": "5e53e7d9bf65ac4f5cbf211a"

"choiceId": "5e53e7d9bf65ac4f5cbf211b"


推荐阅读