Skip to content

Instantly share code, notes, and snippets.

@ackuser
Forked from afshinm/mongodb-singleton.js
Created November 24, 2016 15:01
Show Gist options
  • Save ackuser/e286f618c72ca18adde13a9f92765449 to your computer and use it in GitHub Desktop.
Save ackuser/e286f618c72ca18adde13a9f92765449 to your computer and use it in GitHub Desktop.
MongoDb singleton connection in NodeJs
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
//the MongoDB connection
var connectionInstance;
module.exports = function(callback) {
//if already we have a connection, don't connect to database again
if (connectionInstance) {
callback(connectionInstance);
return;
}
var db = new Db('your-db', new Server("127.0.0.1", Connection.DEFAULT_PORT, { auto_reconnect: true }));
db.open(function(error, databaseConnection) {
if (error) throw new Error(error);
connectionInstance = databaseConnection;
callback(databaseConnection);
});
};
@johnsoncherian
Copy link

Will this be singleton even if i export the file in multiple different js files.?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment