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) {
  //...
});
peterh
  • 11,875
  • 18
  • 85
  • 108
Philipp Kyeck
  • 18,402
  • 15
  • 86
  • 123

7 Answers7

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

jo_va
  • 13,504
  • 3
  • 23
  • 47
kcbanner
  • 4,050
  • 1
  • 25
  • 18
  • this does exactly what i wanted ... to update all Devices' cids to ''. thx – Philipp Kyeck Jul 15 '11 at 09:00
  • 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? – adir abargil Jul 28 '20 at 10:55
39

Those answers are deprecated. This is the actual solution:

Device.updateMany({}, { cid: '' });
Serdar D.
  • 3,055
  • 1
  • 30
  • 23
21

You have to use the multi: true option

Device.update({},{cid: ''},{multi: true});
Moh .S
  • 1,920
  • 19
  • 19
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 :)

sina
  • 2,103
  • 1
  • 19
  • 26
  • 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 strange – avisk Aug 12 '21 at 02:59
  • 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. – Nick N May 12 '22 at 11:51
1
await Device.updateMany({_id: {$in: cid}},{ $set: {columnNameHere: "columnValueHere"}},{multi:true,upsert: true,new: true});
4b0
  • 21,981
  • 30
  • 95
  • 142
Vivek Kumar
  • 81
  • 1
  • 5
  • 2
    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?](https://meta.stackexchange.com/a/148274/183937) – Steve Mar 27 '22 at 10:40
  • I appreciate your helpful advice. – Vivek Kumar Jul 05 '23 at 07:33
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.

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
    })
}
DragonFire
  • 3,722
  • 2
  • 38
  • 51