How can I update multiple documents in mongoose?

Mongodbnode.jsMongoose

Mongodb Problem Overview


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

Mongodb Solutions


Solution 1 - Mongodb

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

Solution 2 - Mongodb

Those answers are deprecated. This is the actual solution:

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

Solution 3 - Mongodb

You have to use the multi: true option

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

Solution 4 - Mongodb

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

Solution 5 - Mongodb

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.

Solution 6 - Mongodb

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

Solution 7 - Mongodb

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPhilipp KyeckView Question on Stackoverflow
Solution 1 - MongodbkcbannerView Answer on Stackoverflow
Solution 2 - MongodbSerdar D.View Answer on Stackoverflow
Solution 3 - MongodbMoh .SView Answer on Stackoverflow
Solution 4 - MongodbsinaView Answer on Stackoverflow
Solution 5 - Mongodbuser12695590View Answer on Stackoverflow
Solution 6 - MongodbDragonFireView Answer on Stackoverflow
Solution 7 - MongodbVivek KumarView Answer on Stackoverflow