简体   繁体   中英

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! "+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 .

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);
  });
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);

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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