【问题标题】:Mongoose not updating the MongoDB documentMongoose 不更新 MongoDB 文档
【发布时间】:2015-10-04 12:10:16
【问题描述】:

这是我用来更新 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);
        }
      });
    });
});

【问题讨论】:

  • 回调的第二个参数包含响应。像这样调用function(err,response),然后在console.log(response.response) 中调试。对象中有键,其中“n”是受影响的文档数,“nMatched”是与查询条件匹配的文档数。您可能不匹配文档。检查您在_id 中拥有的数据类型的架构定义。这是现有的收藏吗?猫鼬希望它默认被称为“问题”而不是“问题”,除非你覆盖它。
  • 未定义 console.log(res.response);架构没有问题,因为我使用它在我的项目中查找并插入另一条路线,问题仅发生在更新中。
  • response.response.update() 回调的结果。不是快速请求中的res
  • 同样的结果未定义

标签: node.js mongodb mongoose


【解决方案1】:

感谢您的支持,尝试了您的解决方案 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);
      });
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    • 2021-10-23
    • 2021-03-26
    • 2011-12-04
    • 2016-10-15
    • 1970-01-01
    • 2020-12-04
    相关资源
    最近更新 更多