我如何更新猫鼬中的多个文档 [英] how can i update multiple documents in mongoose

查看:55
本文介绍了我如何更新猫鼬中的多个文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了以下脚本:

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

MongoDB具有"multi"标志,用于更新多个文档,但是我无法使它与mongoose一起使用.这还不支持,还是我做错了什么?!

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) {
  //...
});

推荐答案

当前,我相信猫鼬中的update()存在一些问题,请参见: https://groups.google.com/forum/#%21topic/mongoose -orm/G8i9S7E8Erg https://groups.google.com/d/topic/mongoose- orm/K5pSHT4hJ_A/讨论.

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.

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

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

更早的解决方案(猫鼬5+版本之后折旧)

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) { ... });

新解决方案

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

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

我相信Mongoose将您的Cid包装在$ set中,因此这与在mongo shell中运行相同的更新不同.如果在shell中运行该文件,则所有文档都将被一个cid: ''替换为一个.

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: ''.

这篇关于我如何更新猫鼬中的多个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆