Mongoose skip, limit and count

Mongoose skip, limit and count

Problem

I am working on a node project where I apply filter and pagination for a grid.

I need the found items, the totals found from the query and the total items in the Mongodb collection.

My query is like (coffeescript):

projects.find(query).limit(10).skip(skip).select(q).exec (err, items) ->
      projects.count().exec (err, count) ->
        itemsTotals = count
        itemsFound = items.length

But if my query returns a result larger than ‘limit’ variable then the number of found items is the limit so or I add a third query or I use the aggregation framework directly.

Do I really need the two query (projects.find and projects.count)?

It is possible to get the two values (total found and total of the collection) with a single mongoose query (and maybe limit the result of returned items directly in the query)?

Problem courtesy of: Ronnie

Solution

You can’t. You need to execute find() with limit and count(), but take into account that you are duplicating the number of queries, you are slowing down the system. Instead of executing a count() you could store into memory the total length and atomically increment it when you do an insert(). When the server starts do a count() to initialize the variable.

Solution courtesy of: Gabriel Llamas

Discussion

Leave a Reply

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