开发者

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

开发者 https://www.devze.com 2023-03-08 04:22 出处:网络
I am using the node-mongodb-native drivers and I am looking for a way to open a persistent database connection rather than opening/clos开发者_StackOverflow社区ing it each time.

I am using the node-mongodb-native drivers and I am looking for a way to open a persistent database connection rather than opening/clos开发者_StackOverflow社区ing 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消