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

DEPRECATED: This post has been marked as deprecated and may no longer 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: #nosql #nodejs
Thomas Hunter II Avatar

Thomas is the author of Advanced Microservices and is a prolific public speaker with a passion for reducing complex problems into simple language and diagrams. His career includes working at Fortune 50's in the Midwest, co-founding a successful startup, and everything in between.