Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to open a persistent (mongo) database connection in NodeJS

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?

like image 847
mrwooster Avatar asked May 25 '11 18:05

mrwooster


1 Answers

My solution:

getClient = function(cb) {
    if(typeof client !== "undefined") {
        return cb(null, client);
    } else {
        db.open(function(err, cli) {
            client = cli;
            getClient(cb);
        });
    }
}

Now, instead of

db.open(function(err, client) {
    ...stuff...
});

Do:

getClient(function(err, client) {
    ...stuff...
});

Your first db call opens a connection, the others use that connection.

BTW: suggestions on checking that client is still alive?

like image 150
joe Avatar answered Oct 23 '22 22:10

joe