简体   繁体   English

在Mongoose中一次更新多个文档的最佳方法

[英]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 我想使用Mongoose在我的nodejs后端中通过条件更新多个条件

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 想一次通话更新

To do this with one query, you can use updateMany() method with $in operator: 要对一个查询执行此操作,您可以将updateMany()方法与$ in运算符配合使用:

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

you can update it using : 您可以使用更新它:

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

To do this with single query use db.collection.updateMany(). 为此,请使用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.' });
        }
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM