使用findOne然后save()来替换文件,mongoose

时间:2014-11-11 18:21:10

标签: node.js mongodb mongoose

我想在我的架构中使用验证。因此,我无法使用findOneAndUpdate(?)。我必须使用保存。

问题是,如果我使用findOne,然后用我要替换它的对象替换该对象,它将不再具有保存功能。

mongoose.model('calculations').findOne({calcId:req.params['calcId']}, function(err, calculation){
    if(err) {errHandler.serverErr(err, res, 'Something went wrong when trying to update a calculation'); return;}
    calculation = calculationToReplace;
    calculation.save(function(err, calc){ //No longer exists
      if(err) {errHandler.serverErr(err, res, 'Something went wrong when trying to update a calculation'); return;}
      res.send(200);
    });
  });

这必须是一项常见任务,但我无法找到任何解决方案。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:4)

有一个简单的解决方案(现在很老)问题。 在我的情况下,我必须有一个findOneAndUpdate upsert返回更多关于发生的事情的信息。所以我的解决方案是逐步完成使用for循环更新对象的过程。

(想想你不能复制的原因是doc对象包含一堆“额外”,如版本信息和保存功能以及其他“位”);所以这是我的解决方案。

exports.postData = function(req,res) {
    console.log("will create " + req.body.alias);
    console.log("It is level " + req.body.level);     //OK, all this have to be changed to members of the data! req.body contains all the data sent from the user at this time
    var query = { 'fulltext' : req.body.fulltext};
    console.log("Checkking if " + req.body.fulltext + " exists")
    Skill.findOne(query, function (err,doc){
        if(err) return res.status(500).send(err)
        if (!doc){
            console.log(req.body.fulltext + " not found!")
            var newdoc = new Skill(req.body);
            newdoc.save(function(err){
                if(err) return res.status(500).send(err)
                console.log(newdoc.fulltext + " created as " + newdoc._id);
                return res.status(200).send({_id: newdoc._id, alias: newdoc.alias})
            })

            return res.status(200).send('blal')
        } else {
            console.log(req.body.fulltext + " found!")
            for (var id in req.body ){
                doc[id]= req.body[id];
            }
            doc.save( function(err){
                if(err) return res.status(500).send(err)
                return res.status(200).send({_id: doc._id, alias: doc.alias})
            })


            //return res.status(200).send({_id: doc._id, alias: doc.alias})
        }

答案 1 :(得分:0)

是的,有办法。您可以阅读mongoose文档here。看看下面的代码。

Tank.findById(id, function (err, tank) {
  if (err) return handleError(err);

  tank.size = 'large';
  tank.save(function (err) {
    if (err) return handleError(err);
    res.send(tank);
  });
});

这种方法包括首先从Mongo中检索文档,然后发出更新命令(通过调用save来触发)。

答案 2 :(得分:0)

我没有测试过以下内容,所以我不确定这是否正常但它可能应该没问题:

交换:

 calculation = calculationToReplace;

用这个:

 for (var key in calculationToReplace)
   if(typeof calculation[key] !== 'function')
     calculation[key] = calculationToReplace[key];
相关问题