From 6b6c289d79d62cedb5c44f31ddb990d23b96b68a Mon Sep 17 00:00:00 2001 From: Sasha <64744993+r1tsuu@users.noreply.github.com> Date: Tue, 25 Feb 2025 23:22:47 +0200 Subject: [PATCH] fix(db-mongodb): `hasNextPage` with polymorphic joins (#11394) Previously, `hasNextPage` was working incorrectly with polymorphic joins (that have an array of `collection`) in MongoDB. This PR fixes it and adds extra assertions to the polymorphic joins test. --------- Co-authored-by: Jarrod Flesch --- .../src/utilities/buildJoinAggregation.ts | 12 +++---- test/joins/int.spec.ts | 31 +++++++++++++++++++ 2 files changed, 37 insertions(+), 6 deletions(-) diff --git a/packages/db-mongodb/src/utilities/buildJoinAggregation.ts b/packages/db-mongodb/src/utilities/buildJoinAggregation.ts index 4af139b5a7..0ffe07e6e1 100644 --- a/packages/db-mongodb/src/utilities/buildJoinAggregation.ts +++ b/packages/db-mongodb/src/utilities/buildJoinAggregation.ts @@ -195,17 +195,17 @@ export const buildJoinAggregation = async ({ const sliceValue = page ? [(page - 1) * limitJoin, limitJoin] : [limitJoin] aggregate.push({ - $set: { - [`${as}.docs`]: { - $slice: [`$${as}.docs`, ...sliceValue], + $addFields: { + [`${as}.hasNextPage`]: { + $gt: [{ $size: `$${as}.docs` }, limitJoin || Number.MAX_VALUE], }, }, }) aggregate.push({ - $addFields: { - [`${as}.hasNextPage`]: { - $gt: [{ $size: `$${as}.docs` }, limitJoin || Number.MAX_VALUE], + $set: { + [`${as}.docs`]: { + $slice: [`$${as}.docs`, ...sliceValue], }, }, }) diff --git a/test/joins/int.spec.ts b/test/joins/int.spec.ts index a83c3b3f92..f3a8812d67 100644 --- a/test/joins/int.spec.ts +++ b/test/joins/int.spec.ts @@ -1205,6 +1205,37 @@ describe('Joins Field', () => { expect(parent.children.docs[1]?.value.id).toBe(child_1.id) expect(parent.children.docs[1]?.relationTo).toBe('multiple-collections-1') + // Pagination across collections + parent = await payload.findByID({ + collection: 'multiple-collections-parents', + id: parent.id, + depth: 1, + joins: { + children: { + limit: 1, + sort: 'title', + }, + }, + }) + + expect(parent.children.docs).toHaveLength(1) + expect(parent.children?.hasNextPage).toBe(true) + + parent = await payload.findByID({ + collection: 'multiple-collections-parents', + id: parent.id, + depth: 1, + joins: { + children: { + limit: 2, + sort: 'title', + }, + }, + }) + + expect(parent.children.docs).toHaveLength(2) + expect(parent.children?.hasNextPage).toBe(false) + // Sorting across collections parent = await payload.findByID({ collection: 'multiple-collections-parents',