dev4Fun
dev4Fun

Reputation: 1050

Return count before limit and skip applied with mongoose

I have a schema defined in mongoose. When I want to retrieve all the items I call

  Item
  .find()
  .limit(limit)
  .skip(skip)
  .exec(function (err, Items) {
    if(err) { return handleError(res, err); }
    return res.json(200, Items);
  });

In future I want perform some filtering and then count the number of results. How can I include the number of results in the response before limit and skip applied?

I tried including count() after find, but had no luck making it working. What am I missing?

Upvotes: 1

Views: 2659

Answers (1)

Fabrício Matté
Fabrício Matté

Reputation: 70159

I believe two queries are necessary, you can execute them in parallel:

var Promise = require('bluebird');
Promise.all([
    Item.find().limit(limit).skip(skip).exec(),
    Item.count().exec()
]).spread(function(items, count) {
    res.json(200, { items: items, count: count });
}, function(err) {
   handleError(res, err);
});

Note that I've adapted the JSON response format in order to fit in a new property containing the count -- I've changed the response from an array to { items: Array, count: Number }.

Calling .exec() without passing a callback returns a Mongoose Promise. In the example above, I'm using Bluebird (npm install bluebird) to manage the asynchronous flow, but you could use any other library of your choice as well.

Upvotes: 6

Related Questions