0

I want to export variable 'result_array' from './models/devices-client.js' below

var config = require('./config');
var MongoClient = require('mongodb').MongoClient;

MongoClient.connect(config.dbadmin_uri, function (err, db) {
if (err) throw err;
// console.log('Successfully connected');
var collection = db.collection('repvpn2');
collection.find().toArray(function (err, result_array) {
// console.log('Found results:', result_array);
    module.exports.Hosts = result_array;
    db.close();
    });
});    

but when import in the other file it prints 'undefined' ?

var Hosts = require('./models/devices-client').Hosts;
console.log(Hosts);
irom
  • 3,316
  • 14
  • 54
  • 86
  • possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Felix Kling Jun 24 '15 at 18:34
  • `MongoClient.connect()` is asynchronous; in other words, it may take a (short) while before it is finished and calls the callback function that sets `module.exports.Hosts`. Until that time, for instance right after calling `require()`, that export will be undefined. – robertklep Jun 24 '15 at 18:35

1 Answers1

0

let your module take an async function callback.

// JavaScript source code
var config = require('./config');
var MongoClient = require('mongodb').MongoClient;
module.exports = function (callback) {
    MongoClient.connect(config.dbadmin_uri, function (err, db) {
        if (err) throw err;
        // console.log('Successfully connected');
        var collection = db.collection('repvpn2');
        collection.find().toArray(function (err, result_array) {
            // console.log('Found results:', result_array);
            callback(err, result_array);
            db.close();
        });
    });
}

require('./models/devices-client')(function callback(err,Hosts) {
   //Hosts Here
});
Hyo Byun
  • 1,196
  • 9
  • 18
  • $ node repcert.js /home/irek/repvpn/node_modules/mongodb/lib/utils.js:97 process.nextTick(function() { throw err; }); ^ ReferenceError: results_array is not defined at /home/irek/repvpn/models/devices-client.js – irom Jun 24 '15 at 18:50
  • 1
    Typo, `result_array` not `results_array`. sry – Hyo Byun Jun 24 '15 at 18:51