简体   繁体   中英

Mongoose skip, limit and count

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)?

I haven't found a better answer yet but I have found this option which is worth mentioning. The obvious drawback is that the DB is returning a larger dataset.

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

I found this here

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM