node.js - 使用 findOne 然后 save() 替换文档,mongoose

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

这肯定是一个常见的任务,但我找不到任何解决方案。我该如何解决这个问题?

最佳答案

对于您的(现在已经很老的)问题有一个简单的解决方案。 就我而言,我必须有一个 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})
        }

关于node.js - 使用 findOne 然后 save() 替换文档,mongoose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26871720/

相关文章:

javascript - 在 mongodb 中保存和执行 IP 排序的最佳方法?

Node.js - Mongoose - 检查集合是否存在

node.js - Sequelize 使用包含和连接表创建事务

javascript - 在 Express.js 中,为什么我下载的文件大小与服务器文件大小不同?

oracle - 如何在 Windows 中连接 Oracle 11g 和 nodejs?

javascript - 查询时并不总是提供参数

javascript - Promise.all 不等待 firestore 查询循环

php - MongoDB:集合中的重复文档

javascript - 从 API 中提取信息并将其添加到数据库(MEAN 堆栈)

javascript - 创建新的 Mongoose 子文档时出现重复键错误