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.