如何在mongoose中更新多个文档

时间:2011-07-14 14:07:59

标签: mongodb node.js mongoose

我找到了以下脚本:

Device.find(function(err, devices) {
  devices.forEach(function(device) {
    device.cid = '';
    device.save();
  });
});

MongoDB有多个文件更新的“多”标志,但我无法使用mongoose。这还没有得到支持,还是我做错了什么?!

Device.update({}, {cid: ''}, false, true, function (err) {
  //...
});

6 个答案:

答案 0 :(得分:72)

目前我相信Mongoose中的update()存在一些问题,请参阅: https://groups.google.com/forum/#%21topic/mongoose-orm/G8i9S7E8Erghttps://groups.google.com/d/topic/mongoose-orm/K5pSHT4hJ_A/discussion

但是,请查看更新文档:http://mongoosejs.com/docs/api.html(在模型下)。定义是:

早期解决方案(在mongoose 5+版本之后弃用)

Model.update = function (query, doc, options, callback) { ... }

您需要在对象中传递选项,因此您的代码将是:

Model.update = function ({}, {cid: ''}, {multi: true}, function(err) { ... });

新解决方案

Model.updateMany = function (query, doc, callback) { ... }

Model.updateMany = function ({}, {cid: ''}, function(err) { ... });

我相信Mongoose将你的cid包装在$ set中,所以这与在mongo shell中运行相同的更新不同。如果您在shell中运行该文档,则所有文档将被替换为具有单个cid: ''的文档。

答案 1 :(得分:16)

您必须使用multi:true选项

Device.update({},{cid: ''},{multi: true});

答案 2 :(得分:10)

不建议使用这些答案。这是实际的解决方案:

Device.updateMany({}, { cid: '' });

答案 3 :(得分:1)

mongoose documents中所述

这是我们的处理方式:

db.collection.updateMany(condition, update, options, callback function)

所以这是一个基于文档的示例:

    // creating arguments
    let conditions = {};
    let update = {
        $set : {
      title : req.body.title,
      description : req.body.description,
      markdown : req.body.markdown
      }
    };
    let options = { multi: true, upsert: true };

    // update_many :)
    YourCollection.updateMany(

      conditions, update, options,(err, doc) => {
        console.log(req.body);
        if(!err) {
          res.redirect('/articles');
        }
        else {
          if(err.name == "ValidationError"){
            handleValidationError(err , req.body);
            res.redirect('/new-post');
          }else {
            res.redirect('/');
          }
        }
      });

这对我来说很好,希望对您有帮助:)

答案 4 :(得分:1)

@sina提到:

let conditions = {};
let options = { multi: true, upsert: true };

Device.updateMany(conditions , { cid: '' },options );

您可以在options之后添加回调函数,但这不是必需的。

答案 5 :(得分:0)

你可以试试下面的方法

try {
    const icMessages = await IcMessages.updateMany({
        room: req.params.room
    }, {
        "$set": {
            seen_status_2: "0"
        }
    }, {
        "multi": true
    });
    res.json(icMessages)

} catch (err) {
    console.log(err.message)
    res.status(500).json({
        message: err.message
    })
}
相关问题