如何在猫鼬中更新多个文档?
我发现了以下脚本:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
目前我认为 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+ 版本后已弃用)
您需要在对象内传递选项,因此您的代码将是:
新解决方案
我相信 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)
You need to pass the options inside an object, so your code would be:
New Solution
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: ''
.这些答案已被弃用。这是实际的解决方案:
Those answers are deprecated. This is the actual solution:
您必须使用 multi: true 选项
You have to use the multi: true option
正如 mongoose 文档中提到的,这就是我们这样做的方式:
db.collection.updateMany(condition, update, options,callback function)
所以这是一个基于文档的示例:
这对我来说效果很好,我希望它有帮助:)
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:
this worked fine for me, I hope it helps :)
正如 @sina 提到的:
您可以在
options
之后添加回调函数,但这不是必需的。as @sina mentioned:
you can add a callback function after
options
but it's not necessary.您可以尝试以下方法
You can try the following way
使用猫鼬:
链接: 文档
示例:
Using Mongoose:
Link: Documentation
Example:
这是基于猫鼬文档的正确方法。
await MyModel.updateMany({}, { $set: { name: 'foo' } });
this is the correct way based on mongoose documentation.
await MyModel.updateMany({}, { $set: { name: 'foo' } });