What's the best practice for MongoDB connections on Node.js?
I like MongoJS a lot. It lets you use Mongo in a very similar way to the default command line and it's just a wrapper over the official Mongo driver. You only open the DB once and specify which collections you'll be using. You can even omit the collections if you run Node with --harmony-proxies
.
var db = require('mongojs').connect('mydb', ['posts']);server.get('/posts', function (req, res) { db.posts.find(function (err, posts) { res.send(JSON.stringify(posts)); });});
- Option A is not a great idea since there is no guarantee that the DB will be finished opening before an HTTP request is handled (granted this is very unlikely)
- Option C is also not ideal since it needlessly opens and closes the DB connection
The way that I like to handle this is using deferreds/promises. There are a bunch of different promise libraries available for Node but the basic idea is to do something like this:
var promise = new Promise();db.open(function(err, db) { // handle err promise.resolve(db);});server.get('/api/something', function doSomething(req, res, next) { promise.then(function(db) // do something });});
I believe Mongoose handles connections in a way that vaguely resembles this.