Mongoose没有更新MongoDB文档

时间:2015-07-15 12:38:28

标签: node.js mongodb mongoose

这是用于更新mongoDB中文档的nodejs代码,req.body包含作为post请求发送到nodejs服务器的文档, 它没有抛出任何错误,但也没有更新文档,任何建议为什么会发生这种情况;

    router.route('/results').post(function(req,res){
        var toupdate = req.body;
        delete toupdate._id;
        console.log(toupdate)
        Question.update({_id:req.body._id}, toupdate, function(err){
            if(err){
                console.error(err.stack);
            }
        });
// even tried Question.update({_id:req.body._id}, {$set:{questions:toupdate.question}});
    });

我也尝试过使用findById,然后这次保存文件得到500作为回复:

router.route('/results').post(function(req,res){
    var toupdate = req.body;
    delete toupdate._id;
    console.log(toupdate)

    Question.findById(eq.body._id, function (err, tank) {
      if (err){ 
                console.log(err.stack);
                return handleError(err);
            }
    toupdate.save(function (err){
    if (err){
        console.log(err.stack);
        return handleError(err);
        }
      });
    });
});

1 个答案:

答案 0 :(得分:0)

感谢您的支持,尝试了您的解决方案JohnnyHK但它没有用,但找到了更新文档的方法,必须将req.body的字段分配给对象的字段,这里:

router.route('/results').post(function(req,res){
    Question.findOne(req.body._id, function (err, questions) {
      if (err) return handleError(err.stack);
               questions.question = req.body.question;
                questions.options = req.body.options; 
                questions.difficulty = req.body.difficulty;
                questions.type = req.body.type;
                questions.answer = req.body.answer;
                questions.domainof = req.body.domainof;
                questions.topic = req.body.topic;
                questions.weightage = req.body.weightage;        
                questions.created_by = req.body.created_by;
    questions.save(function (err){
    if (err) return handleError(err.stack);
        console.log(questions);
      });
    });
});