diff --git a/lib/mongoose-aggregate-paginate.js b/lib/mongoose-aggregate-paginate.js index 81e92c6..5f35de3 100644 --- a/lib/mongoose-aggregate-paginate.js +++ b/lib/mongoose-aggregate-paginate.js @@ -89,7 +89,7 @@ function aggregatePaginate(query, options, callback) { const allowDiskUse = options.allowDiskUse || false; const isPaginationEnabled = options.pagination === false ? false : true; - const q = this.aggregate(); + let q = this.aggregate(); if (query.options) q.options = query.options; @@ -125,7 +125,13 @@ function aggregatePaginate(query, options, callback) { let promise; if (options.useFacet && !options.countQuery) { - const [pipeline, countPipeline] = constructPipelines(); + let [pipeline, countPipeline] = constructPipelines(); + const match = pipeline[0]?.$match; + if (match) { + pipeline.shift(); + countPipeline.shift(); + q = q.match(match); + } promise = q .facet({ docs: pipeline,