# Passing Database connection

I wanted to open Database (Mongo) connection only once when I start application and share the same connection across the application. What am doing as part of app.js is

Creating connection

var dbConnection = mongoose.createConnection(config.database.address, config.database.dbName, config.database.port);


passing dbConnection in every route call

require('./services/MasterServices')(app , dbConnection);


Is it right approach or anything wrong here?

-

## migrated from stackoverflow.comDec 9 '12 at 0:57

This question came from our site for professional and enthusiast programmers.

Does this code work for you, or are you having problems with it? –  Matt Ball Dec 8 '12 at 19:01
I do not have any problem, I'm asking if something wrong with the design or any better approach available there. –  Siva Dec 8 '12 at 19:38

You can use the connect function, which returns the default connection.

Just add mongoose.connect('mongodb://username:password@host:port/database'); whenever you need it.

-
Hi, So I should create connection in app.js and use connect method (in different class) to get connection reference? –  Siva Dec 8 '12 at 20:05

if you have a module which looks after your db interaction, nodejs returns singleton objects for your module. This means you can create a connection in your module:

var connection mongoose. createConnection(); //only ever set up once. The first time it is required

exports.getConnection = function (cb){
if(! connection) {
connection =  mongoose.createConnection();
cb(undefined,connection);
}
else cb(undefined, connection);
};


Just an option.

-

You could separate the connection into a file like "db.js", and then require it when necessary. So for example:

// db.js
var mongoose = require('mongoose'),
config = require('./config.js');

module.exports = mongoose.createConnection(

// route.js