Mongoose:findByIdAndUpdate不更新文档

时间:2017-04-17 09:00:53

标签: node.js mongodb mongoose

当用户选择特定选项时,我想将voteCount增加1 。数据看起来像这样 -

{
    "_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
}

我试过了 -

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

不会更新voteCount ,我收到此消息 -

更新数据时出错了! MongoError:无法使用非数字参数递增:{options:{voteCount:1,name:“Dhoni”}}
未定义

我在哪里做错了? 请帮助

2 个答案:

答案 0 :(得分:1)

更新了一点@Veeram解决方案。这是工作代码 -

obj={
  add:function(){
    var plane="test";
    this.bird="test2";
  }//plane gets deleted right here as it isnt used anymoreand it was never part of obj
};

obj.add();
obj.plane;//never existed
console.log(obj.bird);

答案 1 :(得分:0)

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

});