promised-mongo
A complete rewrite of mongojs to support promises. In a break with previous versions, this library only supports promises, and not callbacks.
Install
promised-mongo is available through npm:
npm install promised-mongo
Compatability with previous versions
I no longer use Q for promises. This means that you can't use
.done()
at the end of promise chains. To turn on compatability with previous versions, you can
call the compatible()
function:
var pmongo = ;
Other than dropping support for callbacks, I have tried to make sure that the new library is compatible with the old tests (see the legacy_tests folder).
How I write JavaScript
I like using async functions from current EMCAScript proposals. This makes node amazingly easier to understand. An example from the tests:
;
Isn't it so much easier to understand? The downsides (of course there had to be some) is that since this is so bleeding edge, editor support and debugging support are varied and patchy, and there's a chance that the feature won't even make it to the final language specification.
This is compiled to ES5 using babel.
Documentation
The documentation below refers to an older version. Most of it should still work the same however. Watch this space for improvements.
Usage
Use promised-mongo just like mongojs, except that you use the returned promise instead of a callback.
var pmongo = ;var db = ;
The connection string should follow the format desribed in the mongo connection string docs. Some examples of this could be:
// simple usage for a local dbvar db = ;// the db is on a remote server (the port default to mongo)var db = ;// we can also provide some credentialsvar db = ;// connect now, and worry about collections latervar db = ;var mycollection = db;
After we connected we can query or update the database just how we would using the mongo API with the exception that the functions return
a promise for the result rather than the result itself. Cursor operations such as find()
and sort()
return a cursor; to get a
promise for the result, you have to force evaluation using toArray()
. Alternatively, you can just call then()
on the cursor and it will call toArray()
for you, returning a promise. The function findOne()
returns a promise immediately, not a cursor.
Note that due to limitations in the Q promise library, you should call .done()
at the end of
any promise chain you aren't returning, in order to throw any uncaught exceptions. For brevity, the examples in this readme don't do that.
// find everythingdbmycollection;// find everything, but sort by namedbmycollection;// find a document using a native ObjectIddbmycollection;// find all named 'mathias' and increment their leveldbmycollection;// find one named 'mathias', tag him as a contributor and return the modified docdbmycollection;// use the save function to just save a documentdbmycollection;
The forEach
function is a special case. The library supports the mongojs style:
// iterate over all whose level is greater than 90.dbmycollection;
It also supports a promise version. If you pass a callback to the forEach
function with only one argument, you get the promise version. The promise will resolve (with undefined
) when the callback has been called for all documents.
// iterate over all whose level is greater than 90 (promise version)dbmycollection;
To access lastErrorObject
returned by findAndModify
using the promises API, use the findAndModifyEx
function:
db.mycollection.findAndModifyEx({
query: { name: 'mathias' },
update: { $set: { tag:'maintainer' } },
new: true
})
.then(function(result) {
var doc = result.result;
var lastErrorObject = result.lastErrorObject;
});
If you provide a callback to find
or any cursor config operation mongojs will call toArray
for you
dbmycollection;dbmycollection;
is the same as
dbmycollection;dbmycollection;
If you are using the promises API, you must call toArray() on cursors before a promise can be obtained. E.g.:
db.mycollection.find().limit(2).skip(1).toArray()
.then(function (docs) {
// ...
});
For more detailed information about the different usages of update and querying see the mongo docs
Streaming cursors
As of 0.7.0
all cursors are a readable stream of objects.
var JSONStream = ;// pipe all documents in mycollection to stdoutdbmycollection;
Notice that you should pipe the cursor through a stringifier (like JSONStream) if you want to pipe it to a serial stream like a http response.
Tailable cursors
If you are using a capped collection you can create a tailable cursor to that collection by adding tailable:true
to the find options
var cursor = dbmycollection;// since all cursors are streams we can just listen for datacursor;
Note that you need to explicitly set the selection parameter in the find
call.
Database commands
With promised-mongo you can run database commands just like with the mongo shell using db.runCommand()
db;
or db.collection.runCommand()
dbthings;
Replication Sets
Promised-mongo can also connect to a mongo replication set by providing a connection string with multiple hosts
var db = ;
For more detailed information about replica sets see the mongo replication docs
API
This API documentation is a work in progress. To maintain compatibility with mongojs, all functions can accept a callback. If no callback is specified, a promise is returned.
Collection
db.collection.aggregate([pipeline], callback)
db.collection.count([query], callback)
db.collection.createIndex(keys, options, [callback])
db.collection.distinct(field, query, callback)
db.collection.drop([callback])
db.collection.dropIndex(index, [callback])
db.collection.dropIndexes([callback])
db.collection.ensureIndex(keys, options, [callback])
db.collection.find([criteria], [projection], [callback])
This function applies a query to a collection. You can get the return value, which is a cursor, or pass a callback
as the last parameter. Said callback receives (err, documents)
db.collection.findOne([criteria], [projection], callback)
Apply a query and get one single document passed as a callback. The callback receives (err, document)