0

so basically, I'm trying to set up a variable that I can directly query the mongodb from. My code looks like this:

db.js

var mongo = require('mongodb').MongoClient;
var DB = null;
var dbURL = 'mongodb://localhost:27017';
exports.connect = function(cb) {

    console.log('meep'); //tracing code

    mongo.connect(dbURL, function(err, db){
        console.log('lmao'); //tracing
        if (err) throw Error('Something has went wrong');
        else { DB=db; console.log(DB); cb();}

    });
    console.log(DB); //returns null
};
//if some other file requires this file as mydbjs for example,
//I want to be able to do mydbjs.db().collection('epik').find(); 
exports.db = function() {
    if (DB === null) throw Error('DB Object has not yet been initialized');
    return DB;
};

Is there a way to do this or do I have to do everything inside the connect function? I'm assuming it could have to do with callback functions or something. Any help is deeply appreciated.

Community
  • 1
  • 1

1 Answers1

0

Your assumption is correct - you can use db variable inside this callback only

function(err, db){
    console.log('lmao'); //tracing
    if (err) throw Error('Something has went wrong');
    else { DB=db; console.log(DB); cb();}
});

Here you can detailed explanation with the examples: nodeJs callbacks simple example

Community
  • 1
  • 1
Andrzej Karpuszonak
  • 8,896
  • 2
  • 38
  • 50
  • Oh okay; I had to reconfigure my code a bit, but it seems to be working great now. I'm just wondering why insertMany doesn't seem to be working? (says insertMany is not a function) Am I using an old dependency version of mongodb? I read somewhere that it was a pretty new addition. – Omar A. Yousry Feb 29 '16 at 10:44