4

I'd like to reuse the MongoClient connection in my routes (I have seen that there are ways using the old connectivity however I'd like to use MongoClient and I'd also like to have a separate DB configuration file

app.js (snippet)

var route = require('route');
app.get("/", route.test);

dbconf.js

var MongoClient = require('mongodb').MongoClient;
var mongourl = 'mongodb://localhost/test';
MongoClient.connect(mongourl, function(err, db) {
  if(err) console.log('Error connecting to ' + mongourl + ': ' + err);
  var coll = db.collection('testcollection');
});

route.js (snippet)

exports.test = function(req, res) {
  //i would like to use the connection created in dbconf.js here
}
Tamas
  • 10,953
  • 13
  • 47
  • 77
  • I wrote an NPM module to do just that: https://npmjs.org/package/mongoconnect (it works as long as you only need to connect to one database) – Hector Correa Jan 10 '14 at 13:38
  • possible duplicate of [node-mongodb-native: How can I share the db api object of the connection callback through my application](http://stackoverflow.com/questions/13863675/node-mongodb-native-how-can-i-share-the-db-api-object-of-the-connection-callbac) – Guido May 22 '14 at 19:55

2 Answers2

1

You could use promises. This way the connection will only be opened once, but you will be able to reuse the database object easily. A very basic version would look somehting like this:

database.js

var mongodb = require('mongodb'),
    Q = require('q');

var MongoClient = mongodb.MongoClient;
var deferred = Q.defer();

MongoClient.connect('mongodb://localhost/test', function(err, database) {
  if (err) {
    deferred.reject(err);
    return;
  }
  deferred.resolve(database);
});

exports.connect = function() {
  return deferred.promise;
};

router.js

var database = require('./database');

exports.test = function(req, res) {
  database.connect().then(function(db) {
    var coll = db.collection('testcollection');
  });
};
Brett
  • 3,825
  • 3
  • 24
  • 27
  • This is not a good practice since it will initialize a connection to the Mongodb database in every request – Reda Dec 20 '17 at 00:41
0

You can do it like this, although it doesn't use a separate dbconf.js file (I don't see the point to be honest as this way the app index will be as small as possible since routing is separated.):

./index.js:

var MongoClient = require('mongodb').MongoClient,
    routes = require('./routes'),
    express = require('express')
    app = new express();
MongoClient.connect('mongodb://localhost/test',function(err,db) {
    if ( err ) {
        // handle error
    }

    routes(app,db);
});

app.listen(8080);

./routes/index.js:

testHandler = require('./test');

var routes = function(app,db) {
    var testhandler = new testHandler(db);

    app.get('/',testhandler.index);
}

exports = module.exports = routes;

./routes/test.js:

var testHandler = function(db) {
    this.index = function(req,res) {
        db.collection('data').find().toArray(function(err,data) {
            res.end(JSON.stringify(data));
        });
    }
}
exports = module.exports = testHandler;
  • In express 4.0 ,router middlewares has been introduced.it can be accessed as _app.use('/',routes)_ . In this case how can u pass the db object to the router middleware??Any idea? – NewtonCode Apr 28 '14 at 12:57