0

我想使用 Mongoose 和 ajax 异步向 mongodb 查询两个不同且不同的东西。

这是代码:

var teams, faculties;
userModel.find({}).sort('-score').exec((err, result) => {
        teams = result;
    });

    userModel.aggregate([{
        "$group": {
            _id: "$faculty",
            average: {
                $avg: "$score"
            }
        }
    }]).exec((err, result) => {
        faculties = result;
    });
res.render('/scoreboard', {
    information: [teams, faculties]
})

是否有更好的实现来处理异步运行的查询?

4

2 回答 2

1

使用async/await我们消除回调并使调用独立。错误特征也可以通过放置 if 与否定条件来简化。

app.get('/myroute', async(req, res) => {
    try {
        const teams = await userModel.find({}).sort('-score')
        const faculties = await userModel.aggregate([{
            "$group": {
                _id: "$faculty",
                average: {
                    $avg: "$score"
                }
            }
        }])    
        res.render('/scoreboard', { information: [teams, faculties] })

    } catch (error) {
        res.status(400).send(error)
    }
})
于 2018-09-03T22:57:36.717 回答
0

可以进行的另一个改进是使用并行运行它,Promise.all因为这些功能彼此独立。

app.get('/myroute', async(req, res) => { 
    const response = await Promise.all([
      userModel.find({}).sort('-score'),
      userModel.aggregate([{
          "$group": {
              _id: "$faculty",
              average: {
                  $avg: "$score"
              }
          }
      }])    
    ]); // response will return as [teams, faculties]
    res.render('/scoreboard', { information: response })
})
于 2018-09-04T01:32:17.997 回答