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