I'm a beginner in nodejs and javascript in general. I want to access a collection and then store my query that I retrieve into an array so later I can do more stuff with that array. However, when I store the results in the array it doesnt outside the function. Here's my code
const http = require('http');
const bodyParser = require('body-parser');
const locations = require('./models/vicitmsLocation');
const async = require('async');
var postcode = [];
locations.getAllTheIncidents({},function (err, results) {
if (err) {
throw err;
} else {
postcode.push(results);
//Here the code works and array will be populated with data I want
console.log(postcode);
}
});
//Here it doesnt work and array is empty.
console.log(postcode);
I understand that this might be an issue with async nature of nodejs and mongo but I cant seem to figure out why this is happening.