如何在猫鼬中更新多个文档?

发布于 2024-11-23 16:29:01 字数 335 浏览 1 评论 0原文

我发现了以下脚本:

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

MongoDB 有用于更新多个文档的“multi”标志,但我无法将此与 mongoose 一起使用。这是尚未支持还是我做错了什么?

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

I found the following script:

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

MongoDB has the "multi" flag for an update over multiple documents but I wasn't able to get this working with mongoose. Is this not yet supported or am I doing something wrong?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

心凉 2024-11-30 16:29:01

目前我认为 Mongoose 中的 update() 有一些问题,请参阅:
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 (其在型号下)。定义是:

早期解决方案(在 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: '' 的文档。

Currently I believe that update() in Mongoose has some problems, see:
https://groups.google.com/forum/#%21topic/mongoose-orm/G8i9S7E8Erg
and https://groups.google.com/d/topic/mongoose-orm/K5pSHT4hJ_A/discussion.

However, check the docs for update: http://mongoosejs.com/docs/api.html (its under Model). The definition is:

Earlier Solution(Depreciated after mongoose 5+ version)

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

You need to pass the options inside an object, so your code would be:

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

New Solution

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

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

I believe that Mongoose wraps your cid in a $set, so this is not the same as running that same update in the mongo shell. If you ran that in the shell then all documents would be replaced by one with a single cid: ''.

迷乱花海 2024-11-30 16:29:01

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

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

Those answers are deprecated. This is the actual solution:

Device.updateMany({}, { cid: '' });
ヅ她的身影、若隐若现 2024-11-30 16:29:01

您必须使用 multi: true 选项

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

You have to use the multi: true option

Device.update({},{cid: ''},{multi: true});
温暖的光 2024-11-30 16:29:01

正如 mongoose 文档中提到的,这就是我们这样做的方式:

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

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

as mentioned in the mongoose documents this is how we do this:

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

so this is an example based on the docs:

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

this worked fine for me, I hope it helps :)

離人涙 2024-11-30 16:29:01
await Device.updateMany({_id: {$in: cid}},{ $set: {columnNameHere: "columnValueHere"}},{multi:true,upsert: true,new: true});
await Device.updateMany({_id: {$in: cid}},{ $set: {columnNameHere: "columnValueHere"}},{multi:true,upsert: true,new: true});
若有似无的小暗淡 2024-11-30 16:29:01

正如 @sina 提到的:

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

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

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

as @sina mentioned:

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

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

you can add a callback function after options but it's not necessary.

合约呢 2024-11-30 16:29:01

您可以尝试以下方法

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

You can try the following way

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
    })
}
才能让你更想念 2024-11-30 16:29:01

使用猫鼬:
链接: 文档

示例:

exports.setHasInsurance = (patientId, hasInsurance) => {
  return Promise.resolve(
    EncounterPush.updateMany(
      { patientId: patientId },
      {
        hasInsurance: hasInsurance,
      }
    )
  );
};

Using Mongoose:
Link: Documentation

Example:

exports.setHasInsurance = (patientId, hasInsurance) => {
  return Promise.resolve(
    EncounterPush.updateMany(
      { patientId: patientId },
      {
        hasInsurance: hasInsurance,
      }
    )
  );
};
黯然 2024-11-30 16:29:01

这是基于猫鼬文档的正确方法。

await MyModel.updateMany({}, { $set: { name: 'foo' } });

this is the correct way based on mongoose documentation.

await MyModel.updateMany({}, { $set: { name: 'foo' } });

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文