mongo adapter for moko


mongo adapter for moko.

npm install moko-mongo
var mongo = require('moko-mongo');
db = yield mongo('mongodb://localhost:27017/test') // opens a connection 
var bob = yield new User({name: 'Bob'});

moko-mongo will use Model.modelName for the collection. For example:

var mongo = yield require('moko-mongo')(connectString);
var User = moko('User').attr('_id').attr('name');
User.use(mongo) // uses 'User' for collection 

If you would like to specify a different collection name, you can do so by passing it as an argument to the plugin.


Raw Kongo collection that you can work with directly.

Queries for all models in the collection given the query. Additional options can be passed in.

Returns an array of instances that match, or an empty array if nothing matched.

var confirmedUsers = yield User.all({confirmed: true}, { sort: {confirmedAt: -1}, limit: 10});

Queries for a specific model in the collection. Returns the first instance to match the query. Additional options can be passed in.

Also supports taking a String for the query for the _id.

If no documents match, returns false.

var user = yield User.get('536b8b39e7449b020000000b'); // Look up via string 
    user = yield User.get({_id: '536b8b39e7449b020000000b'}); // Look up via string 
    user = yield User.get({age: 30}, {sort: {createdAt: -1}}); // Look up via string 

Removes all documents that match the query. Returns the number of documents removed

var removed = yield User.removeAll({deleted: true});
console.log("%d user accounts were removed", removed);

Alias to Model.db.ensureIndex. Lets you make indexes!

Returns a wrapped instances of mquery. See mquery support below.

Returns a wrapped instances of maggregate. See maggregate support below.

Optionally, if don't want it to return Model instances, you can use Model.aggregate(true) to skip wrapping the instances.

moko-mongo provides a wrapped version of the wonderful mquery query builder. To get it, simply call Model.query(). This allows you to build readable and robust queries easily. When approprirate, modella-mongo will return instances of modella models, instead of just documents. Aside from that, it follows the mquery API completely.

  var bob = yield User.query().findOne().where({username: 'Bob'})

moko-mongo uses the maggregate aggregation builder. To use it, simply call Model.aggregate().

This allows you to build readable aggregations easily. By default it wraps responses in Model instances, but can be disabled by passing skipWrap as true. It also follows the maggregate api completely.

var skipWrapping = true;
locations = yield User.aggregate(skipWrapping)
  .group({_id: '$location', userCount: {$sum: 1}});
locations.forEach(function(location) {
  console.log("%s has %d users", location._id, userCount);