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?
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With