I am using the node-mongodb-native drivers and I am looking for a way to open a persistent database connection rather than opening/closing it each time.
A simplified connection might look like this…
var DB = new mongo.Db('vows', new mongo.Server("127.0.0.1", 27017, {})),
connection = DB.open(function(err, db) {
// Here we have access to db
});
How can I make the db object accessible to any module in my application? Rather than having to open the connection for every module separately?
Can this be done using module.exports? Or a global variable?
Edit: Don’t use mongoose, Use something like
mongo-colormongo-client. Then have a single client open in your application. I have./client.jsfile that exports a properly opened and configured mongo client.Mongooseis a solid abstraction on top of mongodb that will allow you to handle mongodb more easily. It’s a worth a look.What you really want to do though is re-open your client every time you do anything with mongo.
You don’t keep an open connection to any other database.
Just place your
DBin a module along with some helper / wrapper functions.