Skip to content

Commit 043a91d

Browse files
fix: ability to query relationships not equal to ID (#6555)
1 parent 54e2d7f commit 043a91d

File tree

2 files changed

+33
-5
lines changed

2 files changed

+33
-5
lines changed

packages/db-mongodb/src/queries/buildSearchParams.ts

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -193,17 +193,19 @@ export async function buildSearchParam({
193193

194194
if (field.type === 'relationship' || field.type === 'upload') {
195195
let hasNumberIDRelation
196+
let multiIDCondition = '$or'
197+
if (operatorKey === '$ne') multiIDCondition = '$and'
196198

197199
const result = {
198200
value: {
199-
$or: [{ [path]: { [operatorKey]: formattedValue } }],
201+
[multiIDCondition]: [{ [path]: { [operatorKey]: formattedValue } }],
200202
},
201203
}
202204

203205
if (typeof formattedValue === 'string') {
204206
if (mongoose.Types.ObjectId.isValid(formattedValue)) {
205-
result.value.$or.push({
206-
[path]: { [operatorKey]: new ObjectId(formattedValue) },
207+
result.value[multiIDCondition].push({
208+
[path]: { [operatorKey]: ObjectId(formattedValue) },
207209
})
208210
} else {
209211
;(Array.isArray(field.relationTo) ? field.relationTo : [field.relationTo]).forEach(
@@ -218,11 +220,13 @@ export async function buildSearchParam({
218220
)
219221

220222
if (hasNumberIDRelation)
221-
result.value.$or.push({ [path]: { [operatorKey]: parseFloat(formattedValue) } })
223+
result.value[multiIDCondition].push({
224+
[path]: { [operatorKey]: parseFloat(formattedValue) },
225+
})
222226
}
223227
}
224228

225-
if (result.value.$or.length > 1) {
229+
if (result.value[multiIDCondition].length > 1) {
226230
return result
227231
}
228232
}

test/collections-rest/int.spec.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -618,6 +618,30 @@ describe('collections-rest', () => {
618618
})
619619
})
620620

621+
it('should query relationships by not_equals', async () => {
622+
const ogPost = await createPost({
623+
relationMultiRelationTo: { relationTo: relationSlug, value: relation.id },
624+
})
625+
await createPost()
626+
627+
const response = await restClient.GET(`/${slug}`, {
628+
query: {
629+
where: {
630+
and: [
631+
{
632+
'relationMultiRelationTo.value': { not_equals: relation.id },
633+
},
634+
],
635+
},
636+
},
637+
})
638+
const result = await response.json()
639+
640+
expect(response.status).toEqual(200)
641+
const foundExcludedDoc = result.docs.some((doc) => ogPost.id === doc.id)
642+
expect(foundExcludedDoc).toBe(false)
643+
})
644+
621645
describe('relationTo multi hasMany', () => {
622646
it('nested by id', async () => {
623647
const post1 = await createPost({

0 commit comments

Comments
 (0)