Created
April 5, 2013 10:57
-
-
Save afshinm/5318436 to your computer and use it in GitHub Desktop.
MongoDb singleton connection in NodeJs
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
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); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I use something like this, but with two main differences:
db.openCalled
.db.authenticate
Another good tip will be to keep all the connection settings in one environment variable as
mongodb://user:password@host:port/database
So, I do something like this: