6

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?

2 Answers 2

5

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?

Sign up to request clarification or add additional context in comments.

1 Comment

The way to see the client is still alive is setTimeout(...) after call getClient, and in the mongo shell, use db.runCommand({serverStatus: 1}).connections to see how many connections there are. I don't think the client will still alive.
1

Edit: Don't use mongoose, Use something like mongo-col or mongo-client. Then have a single client open in your application. I have ./client.js file that exports a properly opened and configured mongo client.


Mongoose is a solid abstraction on top of mongodb that will allow you to handle mongodb more easily. It's a worth a look.

What you really want to do though is re-open your client every time you do anything with mongo.

You don't keep an open connection to any other database.

Just place your DB in a module along with some helper / wrapper functions.

3 Comments

Isn't it too expensive to reopen the client every time?
@BinWang I am wrong about every thing. You shouldn't use mongoose, it sucks. And you shouldnt reopen the client every time.
I'm using generic-pool now. It also opens many clients (connect to mongodb with "poolSize=1" many times) at one time, keep it open and manage the pool itself. Does this affect the benchmark?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.