1
\$\begingroup\$

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?

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

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

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Hi, So I should create connection in app.js and use connect method (in different class) to get connection reference? \$\endgroup\$ – Siva Dec 8 '12 at 20:05
1
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

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');
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy