az_
az_

Reputation: 1503

node.js, node-mongodb-native, DRY connections?

I currently have the following code in every file under ./routes.

var mongo = require('mongodb');
var config = require('../config/config');

var Server = mongo.Server,
    Db = mongo.Db,

var server = new Server(config.DatabaseConfig.host, config.DatabaseConfig.port, {auto_reconnect: true});
db = new Db('test', server);

db.open(function(err, db) {
    if(!err) {
        console.log("Connected to 'test' database");
        db.collection('testcollection', {safe:true}, function(err, collection) {
        });
    }
});

Is there a way for me to open this connection in a central place? Is it even generally accepted to have each object have its own collection in the database?

Upvotes: 0

Views: 142

Answers (1)

Timothy Strimple
Timothy Strimple

Reputation: 23070

I open the database once in the main app entry point and don't call app.listen until the database connection is established.

db.open(function(err) { if(!err) app.listen(3000); });

Upvotes: 1

Related Questions