使用findOne然后save()来replace一个文件mongoose

我想在我的模式中使用validation。 所以我不能使用findOneAndUpdate (?)。 我必须使用保存。

问题是,如果我使用findOne,然后用我将要replace的对象replace,它将不再具有保存function。

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

这一定是一个常见的任务,但我找不到任何解决scheme。 我该如何解决?

有一个简单的解决scheme,你的(现在真的很老)的问题。 在我的情况下,我不得不有一个findOneAndUpdate upsert返回更多的信息发生了什么事。 所以我的解决scheme是通过一个for循环来更新对象。

(想想为什么你不能复制的原因是doc对象包含一些“额外”,如版本信息和保存function和其他“位”); 所以这是我的解决scheme。

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

是的,有一种方法。 你可以在这里阅读mongoose的文档。 看看下面的代码。

 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来触发)。

我没有testing以下,所以我不知道这是否正常工作,但应该可以罚款:

交换这个:

  calculation = calculationToReplace; 

有了这个:

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