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

I am using node-Mongodb-native drivers, and I am looking for a way to open a persistent database connection, rather than opening / closing it every 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 a db object accessible to any module in my application? Instead of opening a connection for each module separately?

Can this be done using module.exports? Or a global variable?

+5
source share
2 answers

: , - mongo-col mongo-client. . ./client.js, mongo.


Mongoose - mongodb, mongodb. .

, , , - .

- .

DB / .

+1

:

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

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

:

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

db , .

BTW: , ?

+5

All Articles