push mongoose query into a global array in node.js

M.Asgari Source

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.

node.jsmongodbmongoose

Answers

answered 8 months ago Akash Dathan #1

Its because nodejs is nonblocking, So, the console.log outside is being executed before the callback of locations.getAllTheIncidents is executed.

So, you have to either use postcode inside the callback or bind locations.getAllTheIncidents inside a promise

comments powered by Disqus