MongoDB Node.js driver collection select doesn't require callback

Multithreaded JavaScript has been published with O'Reilly!
DEPRECATED: This post may no longer be relevant or contain industry best-practices.

Here is the method I was using for the longest time for selecting collections (after following along with numerous tutorials). It seemed that there must be some IO involved with that operation, since they have a callback function.

mongo.db.collection('users', function(err, collection) {
  // No collection, so throw a 500 Server Error
  if (err) {
    console.log(('[     DB] Error finding collection "users"!').red);
    process.exit(1);
  }
  collection.findOne({email: email}, function(err, user) {
    // do stuff
  });
});

But after benchmarking, I realized mongo.db.collection wasn't actually doing any IO. I could run that function one time or 100k times and it would take about the same amount of time. Turns out if you omit the callback function it simply returns the resource. So you can do the following:

var collection = mongo.db.collection('users');
collection.findOne({email: email}, function(err, user) {
  // do stuff
});

Or even more nicely:

mongo.db.collection('users').findOne({email: email}, function(err, user) {
  // do stuff
});

I haven't seen any documentation on this other than noticing it in a code sample in the collection insert code. I was hoping there might be an easier way to select a collection after Tuesdays DetNode Meetup when a bunch of us got into a conversation about it.

Tags: #nodejs #nosql
Thomas Hunter II Avatar

Thomas has contributed to dozens of enterprise Node.js services and has worked for a company dedicated to securing Node.js. He has spoken at several conferences on Node.js and JavaScript and is an O'Reilly published author.