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?
-
\$\begingroup\$ Does this code work for you, or are you having problems with it? \$\endgroup\$Matt Ball– Matt Ball2012年12月08日 19:01:17 +00:00Commented Dec 8, 2012 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– Siva2012年12月08日 19:38:08 +00:00Commented Dec 8, 2012 at 19:38
3 Answers 3
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.
-
\$\begingroup\$ Hi, So I should create connection in app.js and use connect method (in different class) to get connection reference? \$\endgroup\$Siva– Siva2012年12月08日 20:05:19 +00:00Commented Dec 8, 2012 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(
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');