notElonMusk
notElonMusk

Reputation: 374

Best way to update multiple documents at once in Mongoose

I would like to update multiple couments by condtion in my nodejs backend using Mongoose

Trying to update seen notification for all users in the list.

My current method which works but involves lots of calls

  await notificationIDs.forEach(async noticeID => {
        await User.updateOne(
          { "notifications._id": noticeID },
          { $set: { "notifications.$.seen": true } }
        );
      });

Would like to update in one call

Upvotes: 0

Views: 3414

Answers (3)

Pushprajsinh Chudasama
Pushprajsinh Chudasama

Reputation: 7969

To do this with single query use db.collection.updateMany().

 return new Promise((resolve, reject) => {
    UserModel.updateMany({ "notifications._id": notificationIDs }, {$set: { "notifications.$.seen": true } }, { upsert: true, new: true }).exec((err, response) => {
        if (err) {
            reject({ status: 500, message: 'Internal Server Error', data: err });
        } else {
            resolve({ status: 200, message: 'Notification Updated Successfully.' });
        }
    });
});

Upvotes: 1

Saurabh Mistry
Saurabh Mistry

Reputation: 13689

you can update it using :

 await User.update({ "notifications._id": {$in: notificationIDs} },
                       { $set: { "notifications.$.seen": true } },
                       {multi: true});

Upvotes: 1

Cuong Le Ngoc
Cuong Le Ngoc

Reputation: 11975

To do this with one query, you can use updateMany() method with $in operator:

await User.updateMany(
  { "notifications._id": {$in: notificationIDs} },
  { $set: { "notifications.$.seen": true } }
);

Upvotes: 1

Related Questions