Sunday 19 March 2017

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.

In MongoDB I need to access the options array with a variable giving the index number and then increment it's votes property. 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.

Is there any way of accessing the array index with a variable like this?



via swhizzle

No comments:

Post a Comment