Reputation: 141
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?
Upvotes: 0
Views: 571
Reputation: 1002
Read about Positional Operator for handling array updates,
db.collection.update({'_id': questionId, 'options.answer':'answer2'},{"$inc":{"options.$.votes":1}})
Upvotes: 2
Reputation: 340
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.
Upvotes: 1