Skip to content

Instantly share code, notes, and snippets.

@danysantiago
Last active July 26, 2017 20:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danysantiago/7077003 to your computer and use it in GitHub Desktop.
Save danysantiago/7077003 to your computer and use it in GitHub Desktop.
Database Singleton Object - database.js is used throughout the app to access the db object. Using mongodb native drivers the db object contains a pool of connections that are used to make requests to the db. To use this singleton object simply require it and either call getDB() or setDB(). The idea is to use setDB in app.js just after we connect…
/**
Database Singleton Object
database.js is used throughout the app to access the db object. Using mongodb
native drivers the db object contains a pool of connections that are used to
make requests to the db. To use this singleton object simply require it and
either call getDB() or setDB(). The idea is to use setDB in app.js just
after we connect to the db and receive the db object, then in any other file we
need the db require and call getDB
**/
var mongodb = require('mongodb');
var singleton = (function() {
var instance; //Singleton Instance
function init() {
var _db; //Instance db object (private)
//Other private variables and function can be declared here
return {
//Gets the instance's db object
getDB: function() {
return _db;
},
//Sets the instance's db object
setDB: function(db) {
_db = db;
}
//Other public variables and methods can be declared here
};
}
return {
//getInstance returns the singleton instance or creates a new one if
//not present
getInstance: function() {
if (!instance) {
instance = init();
}
return instance;
}
};
})();
module.exports = singleton.getInstance();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment