Last active
July 26, 2017 20:06
-
-
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…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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