mongojs

If you are like me, one of the first things you probably did when you first tried Node.js is to use a database. As it happens, MongoDB became defacto standard, it’s the MySQL of new stacks. When you search for node.js mongodb the first thing that will show up is mongodb (GitHub: mongodb/node-mongodb-native, License: MIT) package.

This driver has been THE Node.js MongoDB driver since pretty much day one for a good reason – it’s a pretty solid driver without any extra cruft. It tries to follow MongoDB API syntax as close as possible, yet it falls short in some places.

This is where mongojs (GitHub: mafintosh/mongojs, License: MIT) by Mathias Buus comes in. It’s a pretty thin wrapper that sits on top of mongodb and comes in at just over 500 lines of code that emulates the official MongoDB API as much as possible.

 

npm install mongojs

Usage

var mongojs = require('mongojs');
var db = mongojs(connectionString, ['mycollection']);

db.mycollection.find(function(err, docs) {
  // docs is an array of all the documents in mycollection
});

// find everything, but sort by name
db.mycollection.find().sort({name:1}, function(err, docs) {
  // docs is now a sorted array
});

// iterate over all whose level is greater than 90.
db.mycollection.find({level:{$gt:90}}).forEach(function(err, doc) {
  if (!doc) {
    // we visited all docs in the collection
    return;
  }
  // doc is a document in the collection
});

// find a document using a native ObjectId
db.mycollection.findOne({
  _id:mongojs.ObjectId('523209c4561c640000000001')
}, function(err, doc) {
  // doc._id.toString() === '523209c4561c640000000001'
});

If you provide a callback to find or any cursor config operation mongojs will call toArray for you:

db.mycollection.find({}, function(err, docs) { ... });
db.mycollection.find({}).limit(2).skip(1, function(err, docs) { ... });

is the same as

db.mycollection.find({}).toArray(function(err, docs) { ... });
db.mycollection.find({}).limit(2).skip(1).toArray(function(err, docs) { ... });

Streaming cursors

Another cool feature unique to mongojs is that all cursors are a readable stream of objects.

var JSONStream = require('JSONStream');

// pipe all documents in mycollection to stdout
db.mycollection.find({}).pipe(JSONStream.stringify()).pipe(process.stdout);

What Else?

Checkout the runnable example and github example repository.

Post navigation

Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *