I want to paginate my query results via $limit and $skip and also get the total count of documents passed the query.
What I do now to paginate results is this:
const startIndex = (page - 1) * limit
const endIndex = page * limit
const resultObject = {}
resultObject.totalCount = await model.countDocuments(query).exec()
if (endIndex < results.totalCount)
resultObject.next = {page: page + 1, limit}
if (startIndex > 0)
results.prev = {page: page - 1, limit}
resultObject.results = await query.limit(limit).skip(startIndex).exec()
This produces 2 problems:
- I execute the query twice (can you even do this in 1?)
- For some reason when my query is an aggregation,
countDocumentsreturns 0 even tho when I executequery.exec()I get the correct results (> 0)
So my question is how can i paginate the results like i do now only with 1 query (and make it work with aggregation queries) while getting the document count so i can build my resultObject