I want my entire node application to use one single mongodb connection, at least that's what I think is better. I wrote this little script and want some feedback on it. Especially if what I'm doing makes sense.
This is my mongodb.js file
'use strict';
// Mongodb module.
var MongoClient = require( 'mongodb' ).MongoClient;
// Database.
var db;
// Working variable.
var working;
// Callbacks array.
var arr = [];
// Exported variable.
module.exports = function( callBack ) {
if ( db ) {
callBack( db );
return;
}
arr.push( callBack );
if ( working ) return;
working = true;
var MongoDB = MongoClient.connect( 'mongodb://127.0.0.1:27017/test',
function( err, res ) {
if( err ) throw err;
console.log( "Connected to MongoDB!" );
db = res;
for ( var i = 0; i < arr.length; i++ ) {
arr[i]( res );
}
arr = [];
}
);
}
This is a file where I include the mongodb.js
var collection;
new require( 'mongodb.js' )(
function( db ) {
collection = db.collection( 'test' );
}
);