Mostafa Ghadimi
Mostafa Ghadimi

Reputation: 6766

async separated queries in nodejs and mongoose

I want to query two separate and different things to mongodb using Mongoose and ajax asynchronously.

Here is the code:

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]
})

Is there a better implementation to handle the queries to run asynchronously?

Upvotes: 0

Views: 166

Answers (2)

Chance
Chance

Reputation: 1654

Using async/await we eliminate the callbacks and leave the calls independent. The error trait can also be simplified by placing if with negation conditions.

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)
    }
})

Upvotes: 1

deerawan
deerawan

Reputation: 8443

Another improvement that can be made is to run it parallely using Promise.all because those functions are independent each other.

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 })
})

Upvotes: 0

Related Questions