Monday, 17 April 2017

Mongoose: findByIdAndUpdate doesn't update the document

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!");
    }
    console.log(doc);
  });

It is does not update the voteCount and I am getting this message -

Something wrong when updating data!
undefined

where am i doing wrong ? Kindly help.



via jay thakur

No comments:

Post a Comment