【问题标题】:Run mongoose save query in forEach loop在 forEach 循环中运行猫鼬保存查询
【发布时间】:2021-01-30 20:54:26
【问题描述】:

我的 graphql 解析器有以下查询:

  setFeatured: async function ({ id }, req) {
    const post = await Post.findById(id)
    const posts = await Post.where('_id').ne(id)
    post.featured = true
    await post.save()
    posts.forEach(pst => {
      pst.featured = false
      await post.save()
    })
    return true
  }

使用上面的代码 sn -p 我想将用户未选择的帖子的状态设置为 false ,反之亦然。

但我在控制台中收到此错误

SyntaxError: await 仅在异步函数中有效 指向 forEach 循环内的await post.save() 行。

如何为每个帖子运行 save() 查询?

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    您还需要将 async 放到传递给 forEach 的回调中。

    posts.forEach(async pst => {
        pst.featured = false
        await post.save()
    })
    
    

    与您的方法不同,如果在任何给定时间有一个特色帖子,您可以将特色字段与帖子分开,并使用一条记录来保存帖子 ID。

    【讨论】:

      猜你喜欢
      • 2017-06-04
      • 1970-01-01
      • 2019-05-26
      • 1970-01-01
      • 2013-11-15
      • 2013-07-12
      • 2019-06-22
      • 2017-12-13
      • 2017-05-08
      相关资源
      最近更新 更多