Skip to content

Commit

Permalink
fix: ability to query relationships not equal to ID (#6555)
Browse files Browse the repository at this point in the history
  • Loading branch information
JarrodMFlesch authored May 29, 2024
1 parent 54e2d7f commit 043a91d
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
14 changes: 9 additions & 5 deletions packages/db-mongodb/src/queries/buildSearchParams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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
}
}
Expand Down
24 changes: 24 additions & 0 deletions test/collections-rest/int.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down

0 comments on commit 043a91d

Please sign in to comment.