Reputation: 151
I want to increment voteCount by 1 when user select a particular option. the data looks like this -
{
"_id": {
"$oid": "58f2ef61af2c5c068c2f1d7a"
},
"pollName": "Who is your favourite cricketer ?",
"options": [
{
"name": "Dhoni",
"_id": {
"$oid": "58f2ef61af2c5c068c2f1d7d"
},
"voteCount": 10
},
{
"name": "Kohli",
"_id": {
"$oid": "58f2ef61af2c5c068c2f1d7c"
},
"voteCount": 6
}
],
"__v": 0
}
I tried this -
// req.body.votedFor is coming fine.
PollModel.findByIdAndUpdate(req.session.pollId, {$inc: { options: {name: req.body.votedFor, voteCount : 1 } }}, {new: true}, function(err, doc){
if(err){
console.log("Something wrong when updating data! "+err);
}
console.log(doc);
});
It is does not update the voteCount and I am getting this message -
Something wrong when updating data! MongoError: Cannot increment with non-numeric argument: {options: { voteCount: 1, name: "Dhoni" }}
undefined
where am i doing wrong ? Kindly help.
Upvotes: 0
Views: 2479
Reputation: 151
Updated a little bit @Veeram Solution. this is the working code -
PollModel.findOneAndUpdate({"_id":req.session.pollId, "options.name": req.body.votedFor}, {$inc:{"options.$.voteCount":1} }, {new: true}, function(err, doc){
if(err){
console.log("Something wrong when updating data! "+err);
}
console.log(doc);
res.send(doc);
});
Upvotes: 1
Reputation: 99
if(req.body.votedFor && req.body.votedFor!='')
setObj['options.name'] = req.body.votedFor;
qobj['options.voteCount']=1;
var updateObj = {};
updateObj['$set'] = setObj;
updateObj['$inc'] = qobj;
PollModel.findByIdAndUpdate({"_id":req.session.pollId},updateObj, {new: true}, function(err, doc){
if(err){
console.log("Something wrong when updating data! "+err);
}
console.log(doc);
});
Upvotes: 0