61

我找到了以下脚本:

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

MongoDB 具有用于更新多个文档的“multi”标志,但我无法使用 mongoose 进行此操作。这还不支持还是我做错了什么?

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

6 回答 6

90

目前我认为update()在 Mongoose 中存在一些问题,请参阅: https ://groups.google.com/forum/#%21topic/mongoose-orm/G8i9S7E8Erg 和https://groups.google.com/d/topic/mongoose- orm/K5pSHT4hJ_A/讨论

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

较早的解决方案(猫鼬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: ''.

于 2011-07-14T16:26:24.267 回答
29

这些答案已被弃用。这是实际的解决方案:

Device.updateMany({}, { cid: '' });
于 2018-10-08T23:31:52.503 回答
19

您必须使用 multi: true 选项

Device.update({},{cid: ''},{multi: true});
于 2017-04-24T10:59:44.213 回答
1

正如猫鼬文件中所提到的,这就是我们这样做的方式:

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('/');
          }
        }
      });

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

于 2020-04-09T16:37:39.147 回答
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
    })
}
于 2021-02-18T09:12:26.030 回答
0

正如@sina 提到的:

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

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

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

于 2020-05-18T10:59:07.957 回答