I am using Node.js and MongoDB atlas which is an online db. I have established a connection to MongoDB atlas and sent a query to the database and retrieved a collection. the collection is returned without any errors. Now I am trying to push the results of the query to an array but the array is still empty.
I have tried to use the console.log() and I see the array becomes empty after the loop. I have noticed that the the second console.log is printed before. I don't know why.
const mongoose = require('mongoose');
var data = function () {
var array = [];
mongoose.connection.collection("organizations").find({}).toArray(function(err, result) {
if (err) throw err;
for(var i = 0; i < result.length; i++)
{
var a = result[i].name;
array.push(a);
console.log(array[i]); //this shows that the array is getting filled and the result is printed correctly.
}
});
console.log(array); //this shows only [] meaning that the array is now empty.
//this is shown in the log before the first log
return array;
};
module.exports = {
data: data,
};