Node.js and MongoDB, reusing the DB object Node.js and MongoDB, reusing the DB object node.js node.js

Node.js and MongoDB, reusing the DB object


You could always write a module which initializes your database connections, and makes them accessible throughout your program. For example:

mongo.js

var mongodb = require('mongodb');module.exports.init = function (callback) {  var server = new mongodb.Server("127.0.0.1", 27017, {});  new mongodb.Db('test', server, {w: 1}).open(function (error, client) {    //export the client and maybe some collections as a shortcut    module.exports.client = client;    module.exports.myCollection = new mongodb.Collection(client, 'myCollection');    callback(error);  });};

app.js

var mongo = require('./mongo.js');//setup express...//initialize the db connectionmongo.init(function (error) {    if (error)        throw error;    app.listen(80); //database is initialized, ready to listen for connections});

randomFile.js

var mongo = require('./mongo.js');module.exports.doInsert = function () {  //use the collection object exported by mongo.js  mongo.myCollection.insert({test: 'obj'}, {safe:true}, function(err, objects) {    if (err)        console.warn(err.message);  });};

I know people talk about pooling, but when I did benchmarking of pooling mongo connections vs. a single connection for all requests, the single connection actually performed better. Granted, this was about a year ago, but I doubt that basic concept has changed. All the requests are asynchronous, so it's not like multiple connections are necessary in order to make simultaneous requests.

As far as MongoClient, I guess that's the new syntax they're encouraging. Either way, it's essentially a client object that you want to keep and make accessible regardless of which style you use.


From your last code snippet, seems like you using Express or similar framework. You can use express-mongo-db to get connection inside req object. This middleware will cache connection for you and share it with other incoming requests:

app.use(require('express-mongo-db')(require('mongodb'), { db: 'test' }))app.post('/employee', function(req, res){    // req.db.collection('names'),insert(req.name)    // Put req.name in database});app.post('/car', function(req, res){    // req.db.collection('names').insert(req.name)    // Put req.car in database});