【问题标题】:How to use async/await with mongoose aggregate如何将 async/await 与 mongoose 聚合一起使用
【发布时间】:2021-07-01 16:10:34
【问题描述】:

当我使用 find() 命令时,我在节点应用程序中使用 async/await,但是否可以对聚合执行相同操作?

有点像

const data = await Model.aggregate([
      {
         $match: {
            "id": id
         }
      }
])

【问题讨论】:

  • 你没试过吗?是的,你肯定能做到。

标签: node.js async-await


【解决方案1】:

是的,你可以这样做 例如

router.get('/something',async function(req, res, next) {
const data = await Model.aggregate([
      {
         $match: {
            "id": id
         }
      }
])
}

【讨论】:

    【解决方案2】:

    试试这个

    const agg = Model.aggregate([
          {
             $match: {
                "id": id
             }
          }
    ])
    
    const data = await agg.exec()
    

    这对我有用,Omega Cube 的回答没有:/

    【讨论】:

      【解决方案3】:

      对于mongodb 4.4,聚合是用exec添加的。

      async function _(){
         const data = await Model.aggregate([
         {
            $match: {
               "id": id
            }
           }
         ]).exec();
         return data
      }
      

      【讨论】:

        猜你喜欢
        • 2019-04-15
        • 2014-03-13
        • 2017-07-02
        • 1970-01-01
        • 1970-01-01
        • 2017-11-05
        • 2014-06-19
        • 2018-01-14
        • 2018-09-12
        相关资源
        最近更新 更多