Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I update multiple documents in mongoose?

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) {   //... }); 
like image 698
Philipp Kyeck Avatar asked Jul 14 '11 14:07

Philipp Kyeck


People also ask

Can you update a Mongoose?

Updating Using QueriesThe save() function is generally the right way to update a document with Mongoose. With save() , you get full validation and middleware.

What is update many in MongoDB?

Introduction to MongoDB updateMany() method The updateMany() method allows you to update all documents that satisfy a condition. The following shows the syntax of the updateMany() method: db.collection.updateMany(filter, update, options)

How do you Upsert a Mongoose?

Upsert. Using the upsert option, you can use findOneAndUpdate() as a find-and-upsert operation. An upsert behaves like a normal findOneAndUpdate() if it finds a document that matches filter . But, if no document matches filter , MongoDB will insert one by combining filter and update as shown below.


2 Answers

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

like image 69
kcbanner Avatar answered Sep 19 '22 04:09

kcbanner


Those answers are deprecated. This is the actual solution:

Device.updateMany({}, { cid: '' }); 
like image 20
Serdar D. Avatar answered Sep 18 '22 04:09

Serdar D.