-1
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?

Debdut
  • 129
  • 1
  • 8

1 Answers1

-1
  var out = [];  // 1.
  companyCollection.find({}).toArray(function (err, result) {
    if (err) {
      console.log (err);
    } else if (result.length) {
      console.log (result); // 3. asynchronous code in callback
      out = result;
      console.log (out); // 4. asynchronous code in callback
    } else {
      console.log ('No documents found');
    }
    db.close();
  });
  console.log (out); // 2. synchronious code
n30n0v
  • 24
  • 3