Search code examples
mongoosees6-promise

Get the results of multiple mongoose queries


I am running multiple aggregate queries using Mongoose and need to have access to the results of these aggregate queries in the same place for the purposes of my application logic.

One thing I need to compute is the mean of a field in a collection and another is the standard deviation.

Company.aggregate([{ $group: { _id: null, mean: {$avg: '$customers'}}}])

Company.aggregate([{ $group: { _id: null, std: {$stdDevPop: '$customers'}}}])

I know I can run exec on both of these individually and use the then() method to acquire the results individually, but how would I go about getting access to these together and then using both of these results together. I guess my question is more about promises more than anything. Is there a way to put the two queries above into an array and then executing a function once both of those promises in the array are resolved?

Is there a way to combine promises so that I can run then() off of the combined promise?


Edit:

let q1 = Company.aggregate([{ $group: { _id: null, mean: {$avg: '$customers'}}}]),
let q2 = Company.aggregate([{ $group: { _id: null, std: {$stdDevPop: '$customers'}}}]),
    queries = [q1, q2].map(q=>q.exec());

Promise.all(queries)
  .then((results)=>{
     const averageCustomers = results[0][0].mean;
     const companies = Company.find({ customers: { $lt: averageCusomters } });
     return companies.exec();
  })
  .then((results)=>{
    //here I only have access to the companies that have less than average customers. 
    //I no longer have access to the average customers across 
    //all companies or their standard deviation.
  })

Solution

  • You are looking for something like Promise.all(). You will get results from all the queries in an array(results).

    let q1 = Company.aggregate([{ $group: { _id: null, mean: {$avg: '$customers'}}}]),
        q2 = Company.aggregate([{ $group: { _id: null, std: {$stdDevPop: '$customers'}}}]),
        queries = [q1, q2].map(q=>q.exec());
    
    Promise.all(queries)
    .then((results)=>{
       console.log(results)
    })