简体   繁体   English

使用变量(MongoDB,Node,Inc)访问嵌套数组中的嵌套对象

[英]Accessing nested object in nested array using a variable (MongoDB, Node, Inc)

I am aware of the myriad of related topics to this question but none seem to answer my problem. 我知道与此问题相关的主题众多,但似乎没有一个问题可以回答我的问题。 It is related to Node and Mongo but I think this is a general Javascript issue. 它与Node和Mongo有关,但是我认为这是一个通用的Javascript问题。

In MongoDB I need to access the options array with a variable giving the index number and then increment it's votes property. 在MongoDB中,我需要使用给出索引号的变量访问options数组,然后递增其votes属性。 An example would be: 一个例子是:

{
    "_id": {
        "$oid": "58ce7c6c39aff90a7c66b0d4"
    },
    "question": "Test",
    "options": [
        {
            "answer": "answer1",
            "option": "Bob Dylan",
            "votes": 2
        },
        {
            "answer": "answer2",
            "option": "Bob Geldof",
            "votes": 0
        }
    ]
}

I then get the index of the array I need to update like so: 然后,我得到需要更新的数组的索引,如下所示:

var votedFor = "answer2";
votedFor = votedFor.match(/\d+/)[0];
var index = parseInt(votedFor) - 1;

Which I then assume the path to the integer to increment would be: 然后我假设要递增的整数的路径为:

var inc = {};
inc["options[" + index + "].votes"] = 1;

Which I would like to pass in like so: 我想这样传递:

db.collection('questions')
.findOneAndUpdate({"_id": questionId}, {$inc : inc }, (err, result) => {
  if (err) return res.send(err)
  res.send(result)
})

Which updates the db like so: 哪个像这样更新数据库:

    {
        "_id": {
            "$oid": "58ce7c6c39aff90a7c66b0d4"
        },
        "question": "Test",
        "options": [
            {
                "answer": "answer1",
                "option": "Bob Dylan",
                "votes": 2
            },
            {
                "answer": "answer2",
                "option": "Bob Geldof",
                "votes": 0
            }
    ],
    "options[1]": {
        "votes": 1
    }
}

Which, as you can see, as opposed to incrementing options[1].votes it has created a new property instead. 如您所见,与增加options[1].votes它创建了一个新属性。

Is there any way of accessing the array index with a variable like this? 有什么办法可以通过这样的变量访问数组索引?

阅读有关用于处理数组更新的Positional Operator的信息,

db.collection.update({'_id': questionId, 'options.answer':'answer2'},{"$inc":{"options.$.votes":1}})

Instead of doing: 而不是做:

var inc = {}; inc["options[" + index + "].votes"] = 1;

You should do: 你应该做:

var inc = {}; inc["options." + index + ".votes"] = 1;

So, you should not use options[0].votes , but options.1.votes , that's how array updates are done in MongoDB. 因此,您不应该使用options[0].votes ,而应该使用options.1.votes ,这就是在MongoDB中完成数组更新的方式。

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

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