0

I'm having some scope issues when trying to save my return data to a parent scope. Here is my source, any help would be greatly appreciated. I can not for the life of me get table to = data.

My data var console.logs correctly its just a problem of scope.

function OpenDB(mongoUrl, callBack){
    var MongoClient = mongodb.MongoClient;
    var url = mongoUrl || "mongodb://" + process.env.IP + "/test";
    MongoClient.connect(url, function(err, db) {
        if(err){
           console.log(err);
        }
      console.log(" Connected correctly to server ");
      callBack(db, function(){
          console.log(" Disconnected from server ");
            db.close();
      });
    }.bind(this));
}
var GetTableAsArray = function(tableName){
    var table = [];
    OpenDB(null, function(db,cb){
        db.collection(tableName).find().toArray(function(err, data){
            if(err){
                console.log(err);
            }
            //this is the problem
            table = data;
            cb();
        });
    });
    return table;
};

1 Answers1

1

By the time GetTablesAsArray function returns, table is still just an empty array. The problem here is that your query happens in an asynchronous way, meaning that you're code doesn't wait for it to be done before proceeding. You can use a callback to execute whatever code you want with the value of tables once it is fetched.

var GetTableAsArray = function(tableName, callback){
    OpenDB(null, function(db,cb){
        db.collection(tableName).find().toArray(function(err, data){
            if(err){
                console.log(err);
            }
            //this is the problem
            table = data;
            cb();
            callback (data);
        });
    });
};

GetTableAsArray('tableName', function (table) {
  console.log(table);
});
dmlittle
  • 964
  • 6
  • 15