diff --git a/lib/mongoose-aggregate-paginate.js b/lib/mongoose-aggregate-paginate.js index 41121d6..45d80d8 100644 --- a/lib/mongoose-aggregate-paginate.js +++ b/lib/mongoose-aggregate-paginate.js @@ -145,10 +145,19 @@ function aggregatePaginate(query, options, callback) { } else { const [pipeline, countPipeline] = constructPipelines(); - const countQuery = options.countQuery + let countQuery = options.countQuery ? options.countQuery : this.aggregate(countPipeline); + if (options.countQuery) { + countQuery = countQuery.group({ + _id: null, + count: { + $sum: 1, + }, + }); + } + if (allowDiskUse) { countQuery.allowDiskUse(true); } @@ -157,17 +166,7 @@ function aggregatePaginate(query, options, callback) { if (query.options) q.options = query.options; - promise = Promise.all([ - q.exec(), - countQuery - .group({ - _id: null, - count: { - $sum: 1, - }, - }) - .exec(), - ]); + promise = Promise.all([q.exec(), countQuery.exec()]); } return promise diff --git a/tests/index.js b/tests/index.js index 9852e09..3d10c18 100644 --- a/tests/index.js +++ b/tests/index.js @@ -294,11 +294,11 @@ describe("mongoose-paginate", function () { }; return Book.aggregatePaginate(aggregate, options).then((result) => { expect(result.docs).to.have.length(10); - expect(result.docs[0].title).to.equal("Book #41"); + expect(result.docs[0].title).to.equal("Book #11"); expect(result.totalDocs).to.equal(100); expect(result.limit).to.equal(10); expect(result.page).to.equal(2); - expect(result.pagingCounter).to.equal(41); + expect(result.pagingCounter).to.equal(11); expect(result.hasPrevPage).to.equal(true); expect(result.hasNextPage).to.equal(true); expect(result.prevPage).to.equal(1);