乐闻世界logo
搜索文章和话题

Mongoose 如何同时更新多个文档?

5 个月前提问
3 个月前修改
浏览次数42

6个答案

1
2
3
4
5
6

在Mongoose中,如果你想同时更新多个文档,可以使用updateMany方法。这个方法允许你根据指定的查询条件来更新所有匹配的文档。下面是一个例子:

假设有一个名为User的模型,该模型代表一个用户集合,我们想要将所有用户的isActive字段从false更新为true

javascript
const mongoose = require('mongoose'); const User = mongoose.model('User', new mongoose.Schema({ isActive: Boolean })); async function updateMultipleUsers() { try { const filter = { isActive: false }; // 定义匹配条件 const update = { isActive: true }; // 定义更新的内容 // 使用updateMany将所有匹配filter的文档的isActive字段更新为true const result = await User.updateMany(filter, update); // result会包含更新操作的结果,例如匹配的文档数和实际更新的文档数 console.log(result); } catch (error) { console.error('Error updating users:', error); } } // 调用函数以执行更新 updateMultipleUsers();

在这个例子中,我们首先定义了一个用于匹配要更新的文档的filter对象,这里它只有一个属性isActive,我们要匹配所有isActivefalse的文档。然后,我们定义了一个update对象来指定要对匹配的文档进行的更新操作,即将isActive设置为true

接着,我们调用User.updateMany方法,并传入这两个对象。这个方法返回一个Promise,所以我们可以使用await关键字等待它的完成。完成后,它会返回一个包含操作结果的对象,其中包括了匹配的文档数量和实际更新的文档数量。

如果需要应用更复杂的更新操作,比如使用MongoDB的更新操作符(例如$set$inc等),你可以在update对象中包含这些操作符。此外,还可以传入一个选项对象来自定义操作的行为,例如是否要返回更新后的文档等。

2024年6月29日 12:07 回复

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)

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

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

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

New Solution

shell
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年6月29日 12:07 回复

Those answers are deprecated. This is the actual solution:

shell
Device.updateMany({}, { cid: '' });
2024年6月29日 12:07 回复

You have to use the multi: true option

shell
Device.update({},{cid: ''},{multi: true});
2024年6月29日 12:07 回复

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:

shell
// 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年6月29日 12:07 回复

await Device.updateMany({_id: {$in: cid}},{ $set: {columnNameHere: "columnValueHere"}},{multi:true,upsert: true,new: true});

2024年6月29日 12:07 回复

你的答案