From 043a91d71999096fecbcba0ac93e714c842f4ab0 Mon Sep 17 00:00:00 2001 From: Jarrod Flesch <30633324+JarrodMFlesch@users.noreply.github.com> Date: Wed, 29 May 2024 13:47:44 -0400 Subject: [PATCH] fix: ability to query relationships not equal to ID (#6555) --- .../src/queries/buildSearchParams.ts | 14 +++++++---- test/collections-rest/int.spec.ts | 24 +++++++++++++++++++ 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/packages/db-mongodb/src/queries/buildSearchParams.ts b/packages/db-mongodb/src/queries/buildSearchParams.ts index 9bf73a87c..98ef348a8 100644 --- a/packages/db-mongodb/src/queries/buildSearchParams.ts +++ b/packages/db-mongodb/src/queries/buildSearchParams.ts @@ -193,17 +193,19 @@ export async function buildSearchParam({ if (field.type === 'relationship' || field.type === 'upload') { let hasNumberIDRelation + let multiIDCondition = '$or' + if (operatorKey === '$ne') multiIDCondition = '$and' const result = { value: { - $or: [{ [path]: { [operatorKey]: formattedValue } }], + [multiIDCondition]: [{ [path]: { [operatorKey]: formattedValue } }], }, } if (typeof formattedValue === 'string') { if (mongoose.Types.ObjectId.isValid(formattedValue)) { - result.value.$or.push({ - [path]: { [operatorKey]: new ObjectId(formattedValue) }, + result.value[multiIDCondition].push({ + [path]: { [operatorKey]: ObjectId(formattedValue) }, }) } else { ;(Array.isArray(field.relationTo) ? field.relationTo : [field.relationTo]).forEach( @@ -218,11 +220,13 @@ export async function buildSearchParam({ ) if (hasNumberIDRelation) - result.value.$or.push({ [path]: { [operatorKey]: parseFloat(formattedValue) } }) + result.value[multiIDCondition].push({ + [path]: { [operatorKey]: parseFloat(formattedValue) }, + }) } } - if (result.value.$or.length > 1) { + if (result.value[multiIDCondition].length > 1) { return result } } diff --git a/test/collections-rest/int.spec.ts b/test/collections-rest/int.spec.ts index 736a6b448..a5006b3e0 100644 --- a/test/collections-rest/int.spec.ts +++ b/test/collections-rest/int.spec.ts @@ -618,6 +618,30 @@ describe('collections-rest', () => { }) }) + it('should query relationships by not_equals', async () => { + const ogPost = await createPost({ + relationMultiRelationTo: { relationTo: relationSlug, value: relation.id }, + }) + await createPost() + + const response = await restClient.GET(`/${slug}`, { + query: { + where: { + and: [ + { + 'relationMultiRelationTo.value': { not_equals: relation.id }, + }, + ], + }, + }, + }) + const result = await response.json() + + expect(response.status).toEqual(200) + const foundExcludedDoc = result.docs.some((doc) => ogPost.id === doc.id) + expect(foundExcludedDoc).toBe(false) + }) + describe('relationTo multi hasMany', () => { it('nested by id', async () => { const post1 = await createPost({