我想在架构中使用验证。因此,我不能使用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);
});
});
这必须是一项常见的任务,但我找不到任何解决方案。我该如何解决?
您的问题(到现在为止已经很老了)有一个简单的解决方案。在我的情况下,我必须拥有一个findOneAndUpdate upsert,该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})
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句