0

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?

az_
  • 1,493
  • 1
  • 16
  • 24

1 Answers1

1

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); });

Timothy Strimple
  • 22,920
  • 6
  • 69
  • 76
  • The way I finally did it, is attaching db to app.db and `module.exports.app = app;`. This way this connection is available anywhere `app` is available. – az_ Jan 08 '13 at 04:22