0

Is there a way to get the contents of variable data outside the function. I am so stuck, looked various forums in stackoverflow and but failed. I am trying to retrieve data from mongoose model and push those results into an array results and when i print results array, i get empty array .

  var results = []
  Model.find({firstName:name}, function(err,data){       
     if(err)
       throw err;

     data.forEach(function(element) {
       console.log(element);
       results.push(element);
     });
 });
 console.log(results) --> []

But when i try to print the data inside the ForEach, I am was get the results, listed below.

0 => { _id: 5dc9953a2168993711903698,
  id: 763,
  firstName: 'Deepak',
  lastName: 'Kalra',
  image_id: 'No',
  logged: false,
  __v: 0 
}
1 => { 
  _id: 5dc995546f0f88372080ea36,
  id: 511,
  firstName: 'Deepak',
  lastName: 'Kalra',
  image_id: 'No',
  logged: false,
  __v: 0 
}

Entire code

  alexa.intent("FirstName", {
     "slots": { "name": "AMAZON.FIRST_NAME" },
     "utterances": [
       "sure {-|name}","{-|name}","my name is {-|name}"
      ]
  },
  function(request, response) {
    var name = 'Deepak';
    try {
      var results = await Model.find({firstName:name});
      console.log(results)
    } catch (error) {
      // Handle error.
    }

   // Model.find({firstName:name}, function(err,data){

      //   if(err)
      //     throw err;
     //   data.forEach(function(element) {
    //     console.log(element);
    //     results.push(element);
     //   });
  // });

     console.log(results);
  });

Is there any solution to fix it. please help me

James K J
  • 605
  • 1
  • 8
  • 20

1 Answers1

1

Because, console.log(results) executed before Model.find was finished.

Two things you can do here:

  • Put console.log(results) inside the callback.
  • Use async/await to get similar behaviour.

Example (callback):

Model.find({firstName:name}, function(err,data){       
    if(err)
      throw err;

    console.log(data); // data is already an array
});

Example (async/await):

try {
  var results = await Model.find({ firstName: name });  
  console.log(results)
} catch (error) {
  // Handle error.
}

Model.find already returns an array of document, so you don't have to run a loop to push them into an array.

UPDATED

alexa.intent("FirstName", {
  "slots": { "name": "AMAZON.FIRST_NAME" },
  "utterances": [
    "sure {-|name}", "{-|name}", "my name is {-|name}"
  ]
},
async function (request, response) {
  var name = 'Deepak';
  try {
    var results = await Model.find({ firstName: name });
    console.log(results)
  } catch (error) {
    // Handle error.
  }
});

Notice the async in front of function.

Shihab
  • 2,641
  • 3
  • 21
  • 29