首页 > 解决方案 > 如果满足条件,更新收藏并发送电子邮件 || Mongo Nodejs

问题描述

我有以下情况 - 我想遍历 db 中的每个元素,并且:

然后:

我的做法:

User.updateMany(
     {
        bumped: false,
        creationDate: {
           $gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
        },
     },
     {
        $set: {
           bumped: true,
        },
     },
     (err, res) => {
        // 
        // What is "res" here? <====== question
     },
  );

我的问题-res回调函数中的参数是什么?

问题2:是否只会为这些满足条件的元素触发回调?

非常感谢!

标签: javascriptnode.jsmongodbmongoose

解决方案


updateMany函数不返回更新的文档。它只返回更新的文档数。

所以在这里你唯一能做的就是首先找到所有的文档并一个一个地迭代,然后可以调用发送邮件功能。

const users = await User.find({
  "bumped": false,
  "creationDate": {
    "$gte": new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
  }
})

const promises = users.map(async(user) => {
  await User.updateOne({ _id: user._id }, { $set: { bumped: true }})
  // Here you can write your send mail function
})

await Promise.all(promises)

推荐阅读