How can I update multiple documents in mongoose?
Asked Answered
V

9

71

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) {
  //...
});
Volvox answered 14/7, 2011 at 14:7 Comment(0)
I
96

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

Insurgency answered 14/7, 2011 at 16:26 Comment(2)
this does exactly what i wanted ... to update all Devices' cids to ''. thxVolvox
why are you show us function definition? this is misleading to think you might suggest us to override custom functions, should you print it as so: Device.updateMany({}, { cid: '' }); just as @Moh .S answered?Espinal
C
41

Those answers are deprecated. This is the actual solution:

Device.updateMany({}, { cid: '' });
Chilton answered 8/10, 2018 at 23:31 Comment(0)
S
21

You have to use the multi: true option

Device.update({},{cid: ''},{multi: true});
Salacious answered 24/4, 2017 at 10:59 Comment(0)
S
4

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

Sudderth answered 9/4, 2020 at 16:37 Comment(2)
This is the only answer that actually worked and yet it only had 0 votes? For some reason it only works with the callback, which is strangeInterference
For the new guys like me, this answer was easier to read and use for a solution. Although, I didn't need the res.redirect portion of the code.Verisimilar
L
1
await Device.updateMany({_id: {$in: cid}},{ $set: {columnNameHere: "columnValueHere"}},{multi:true,upsert: true,new: true});
Laurencelaurene answered 27/3, 2022 at 10:39 Comment(1)
On Stack Overflow, the how is important, but a great part of the quality level of the site comes from the fact that people go to great lengths to explain the why. While a code-only answer get the person who asked the question past whatever hurdle they might be facing, it doesn't do them or future visitors much good in the long run. See Is there any benefit in code-only answers?Gossipy
C
0

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.

Clie answered 18/5, 2020 at 10:59 Comment(0)
M
0

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
    })
}
Monoplane answered 18/2, 2021 at 9:12 Comment(0)
A
0

Using Mongoose: Link: Documentation

Example:

exports.setHasInsurance = (patientId, hasInsurance) => {
  return Promise.resolve(
    EncounterPush.updateMany(
      { patientId: patientId },
      {
        hasInsurance: hasInsurance,
      }
    )
  );
};
Anywheres answered 14/3 at 15:14 Comment(0)
B
-1

this is the correct way based on mongoose documentation.

await MyModel.updateMany({}, { $set: { name: 'foo' } });

Bifocal answered 16/4 at 12:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.