From 73bd69870c4ff8ae92053e77ef95cfae18c142b5 Mon Sep 17 00:00:00 2001 From: Dan Ribbens Date: Mon, 27 Sep 2021 12:52:07 -0400 Subject: [PATCH] fix: pagination estimatedCount limited to near query --- src/collections/operations/find.ts | 8 +++++++- src/utilities/flattenWhereConstraints.ts | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 src/utilities/flattenWhereConstraints.ts diff --git a/src/collections/operations/find.ts b/src/collections/operations/find.ts index 53579f6c683..b867ca8de89 100644 --- a/src/collections/operations/find.ts +++ b/src/collections/operations/find.ts @@ -4,6 +4,7 @@ import executeAccess from '../../auth/executeAccess'; import sanitizeInternalFields from '../../utilities/sanitizeInternalFields'; import { Collection, PaginatedDocs } from '../config/types'; import { hasWhereAccessResult } from '../../auth/types'; +import flattenWhereConstraints from '../../utilities/flattenWhereConstraints'; export type Arguments = { collection: Collection @@ -55,6 +56,7 @@ async function find(incomingArgs: Arguments): Promise { // ///////////////////////////////////// const queryToBuild: { where?: Where} = {}; + let useEstimatedCount = false; if (where) { let and = []; @@ -68,6 +70,10 @@ async function find(incomingArgs: Arguments): Promise { ...and, ], }; + + const constraints = flattenWhereConstraints(queryToBuild); + + useEstimatedCount = constraints.some((prop) => Object.keys(prop).some((key) => key === 'near')); } if (!overrideAccess) { @@ -110,7 +116,7 @@ async function find(incomingArgs: Arguments): Promise { sort, lean: true, leanWithId: true, - useEstimatedCount: true, + useEstimatedCount, }; const paginatedDocs = await Model.paginate(query, optionsToExecute); diff --git a/src/utilities/flattenWhereConstraints.ts b/src/utilities/flattenWhereConstraints.ts new file mode 100644 index 00000000000..0a5bf5c2595 --- /dev/null +++ b/src/utilities/flattenWhereConstraints.ts @@ -0,0 +1,18 @@ +import { WhereField } from '../types'; + +const flattenWhereConstraints = (query): WhereField[] => { + if (!query.where && !query.and && !query.or) { + return Object.keys(query).map((key) => query[key]); + } + if (query.where) { + const whereResult = flattenWhereConstraints(query.where); + return Object.keys(whereResult).map((key) => whereResult[key]); + } + const nested = [...query.or || [], ...query.and || []]; + if (nested.length > 0) { + return nested.flatMap((nest) => flattenWhereConstraints(nest)); + } + return query; +}; + +export default flattenWhereConstraints;