Skip to content

Commit

Permalink
Merge pull request #328 from payloadcms/fix/query-estimate-count
Browse files Browse the repository at this point in the history
fix: pagination estimatedCount limited to near query
  • Loading branch information
DanRibbens authored Sep 27, 2021
2 parents dece5e6 + 73bd698 commit 004ac8d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/collections/operations/find.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -55,6 +56,7 @@ async function find(incomingArgs: Arguments): Promise<PaginatedDocs> {
// /////////////////////////////////////

const queryToBuild: { where?: Where} = {};
let useEstimatedCount = false;

if (where) {
let and = [];
Expand All @@ -68,6 +70,10 @@ async function find(incomingArgs: Arguments): Promise<PaginatedDocs> {
...and,
],
};

const constraints = flattenWhereConstraints(queryToBuild);

useEstimatedCount = constraints.some((prop) => Object.keys(prop).some((key) => key === 'near'));
}

if (!overrideAccess) {
Expand Down Expand Up @@ -110,7 +116,7 @@ async function find(incomingArgs: Arguments): Promise<PaginatedDocs> {
sort,
lean: true,
leanWithId: true,
useEstimatedCount: true,
useEstimatedCount,
};

const paginatedDocs = await Model.paginate(query, optionsToExecute);
Expand Down
18 changes: 18 additions & 0 deletions src/utilities/flattenWhereConstraints.ts
Original file line number Diff line number Diff line change
@@ -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;

0 comments on commit 004ac8d

Please sign in to comment.