问题描述
我找到了以下脚本:
Device.find(function(err, devices) {
devices.forEach(function(device) {
device.cid = '';
device.save();
});
});
MongoDB 具有多"功能.多个文档的更新标志,但我无法使用猫鼬进行此操作.这还不支持还是我做错了什么?
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) {
//...
});
推荐答案
目前我认为 Mongoose 中的 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/G8i9S7E8Ergand 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: ''
.
这篇关于如何在猫鼬中更新多个文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!