var http = require('http');
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/testdb";
var companies = [{'name' : 'Sun Pharma', 'medicine' : [1, 2]},
{'name' : 'Hello Pharma', 'medicine' : [3, 4]},
{'name' : 'Sayan Pharma Ltd.', 'medicine' : [5]}]
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var companyCollection = db.collection ('company');
companies.forEach ((company) => {
companyCollection.insert (company);
});
var out;
companyCollection.find({}).toArray(function (err, result) {
if (err) {
console.log (err);
} else if (result.length) {
console.log (result); // Prints correct array
out = result;
console.log (out); // Prints correct array
} else {
console.log ('No documents found');
}
db.close();
});
console.log (out); // Prints undefined
});
The variable out is assigned equal to result. When result and out are printed within the function scope, it prints correctly, but when I print out outside the function, it's undefined. Why is this happening and how to fix it?