Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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?

share|improve this question

migrated from stackoverflow.com Dec 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

3 Answers 3

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.

share|improve this answer

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.

See http://mongoosejs.com/docs/connections.html

share|improve this answer
    
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

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(
    config.database.address, config.database.dbName, config.database.port);

And then in your routes, you might do something like:

// route.js
var db = require('./db.js');
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.