【问题标题】:Update collection and send email if conditions are met || Mongo Nodejs [duplicate]如果满足条件,则更新收藏并发送电子邮件 || Mongo Nodejs [重复]
【发布时间】:2019-08-18 11:14:27
【问题描述】:

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

  • 如果元素的bumped 字段设置为false
  • 并且创建日期小于 30 天前

然后:

  • bumped 设置为true
  • 向用户发送邮件!

我的做法:

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:是否只会为这些满足条件的元素触发回调?

非常感谢!

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

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

    所以在这里你唯一能做的就是先找到所有的文档,一个一个地迭代,然后可以调用send mail函数。

    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)
    

    【讨论】:

    • 谢谢。但是,我认为 const users = User.find(...) 不需要 await 关键字。还是我错了?甚至编译器都在抱怨它 - “Await 必须在 Async 函数中使用”
    • 你应该只在 async 函数中使用 await
    猜你喜欢
    • 2021-08-25
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    • 1970-01-01
    相关资源
    最近更新 更多