s4f3r71
s4f3r71

Reputation: 46

Mongoose Express.js get result from multiple queries

I am trying to get results from a series of queries on mongodb using async method but unfortunately the object that I generate is undefined outside the async function scope.

      let dataObject = {
         prop1: 1,
         prop2: 2
         ....
      };

      let result = {};

      _.each(dataObject, async function (val, key) {

        let query = [
          {
            $match: {
              x:1
              ....
            }
          }
        ];

        let = MyModel.aggregate(query);
        let data = await q.exec();

          if (data.length > 0) {
            result[key] = data[0].myProp;
            console.log(result); // I can see result here
          }
       });

       console.log('====>>', result); // Here the result is undefined

What I am missing?

Upvotes: 0

Views: 155

Answers (2)

s4f3r71
s4f3r71

Reputation: 46

As a reference I am posting a solution that I found and looks very simple. Instead of using _.each operator I tried to use a simple for loop and also removed the exec() (as suggested by Mohammad) and it worked as expected:

  let dataObject = {
     prop1: 1,
     prop2: 2
     ....
  };

  let result = {};
  let allKeys = Object.keys(dataObject)
   for (key of allKeys) { {

    let query = [
      {
        $match: {
          x:1
          ....
        }
      }
    ];

    let data = MyModel.aggregate(query);

      if (data.length > 0) {
        result[key] = data[0].myProp;
      }
   });

   console.log('====>>', result); // works fine!

Upvotes: 0

Mohammad Yaser Ahmadi
Mohammad Yaser Ahmadi

Reputation: 5051

for this issue you can create a promise function for example getData, dataObject as input argument and the function return result like this :

let async = require('async');
let q = require('q');

const getData = async (dataObject)=>{
  let defer =q.defer();
  let result = []
  input = Object.keys(dataObject)
  async.eachSeries(input , async(key)=>{
    try {
      let query = [
        {
          $match: {
            x:1
            ....
          }
        }
      ];
      let data = await MyModel.aggregate(query).lean();
      if (data.length > 0) {
        result[key] = data[0].myProp;
        console.log(result);
      }
    } catch (error) {
      console.log(error)
    }
  },()=>{
    console.log("finish process")
    defer.resolve(result)// return final data
  })
  return defer.promise
}

in main function call this function(getData) like this :

const mainFunctio = async()=>{
  dataObject
  console.log(start)
  result  = await getData(dataObject)
  console.log(result)
}

Upvotes: 1

Related Questions