1.0.0 • Published 9 years ago

limited v1.0.0

Weekly downloads
3
License
MIT
Repository
github
Last release
9 years ago

limited

Compose $aggregate MongoDB queries for Mongoose as if $push had a $limit operator.

Fetching the "top N commits on each repository with one of these ids" is a hard task due to MongoDB's limitations on $aggregate, specifically the inability to $limit on a $push operator. limited makes this easier for you.

Install

npm install limited --save

limited(options, done)

Configuration options are detailed below.

PropertyDescriptionExample
modelThe mongoose model or raw mongodb collection you want to operate onCommit
fieldThe field you want to group by'repo'
queryOptional filter so that the aggregate doesn't run on the entire collection{ repo: { $in: repoIds } }
sortOptional sort expression as an object{ created: -1 }
limitNumber of documents do you want to retrieve from each match5

A single (albeit complex) query will be issued against the database and you'll get back a list of model documents that match your query requirements, grouped by at most limit documents per field, and sorted by sort.

var _ = require('lodash');
var limited = require('limited');
var models = require('./models');

function getLastCommitInRepositories (ids, done) {
  var options = {
    model: models.Commit,
    field: 'repo',
    query: { repo : { $in: ids } },
    limit: 5,
    sort: { created: -1 }
  };
  limited(options, find);

  function find (err, result) {
    if (err) {
      done(err); return;
    }

    models.Commit
      .find({ _id: { $in: _.flatten(result, 'documents') } })
      .lean()
      .exec(done);
  }
}

The second query isn't executed on your behalf. It's up to you to decide how you want to deal with the document ids you get back from limited.

License

MIT

1.0.0

9 years ago