fix(db-mongodb): querying relationships with where clause as an object with several conditions (#11953)

Fixes https://github.com/payloadcms/payload/issues/11927

When trying to use the following notation:
```ts
const { docs } = await payload.find({
  collection: 'movies',
  depth: 0,
  where: {
    'director.name': { equals: 'Director1' },
    'director.localized': { equals: 'Director1_Localized' },
  },
})
```
Currently, it respects only the latest condition and the first is
ignored.

However, this works fine:
```ts
const { docs } = await payload.find({
  collection: 'movies',
  depth: 0,
  where: {
    and: [
      {
        'director.name': { equals: 'Director1' },
      },
      {
        'director.localized': { equals: 'Director1_Localized' },
      },
    ],
  },
})
```

But this should be an equivalent to
```
 where: {
    'director.name': { equals: 'Director1' },
    'director.localized': { equals: 'Director1_Localized' },
  },
```
This commit is contained in:
Sasha
2025-04-03 16:07:10 +03:00
committed by GitHub
parent d47b753898
commit 857e984fbb
2 changed files with 48 additions and 1 deletions

View File

@@ -81,7 +81,19 @@ export async function parseParams({
[searchParam.path]: searchParam.value,
})
} else {
result[searchParam.path] = searchParam.value
if (result[searchParam.path]) {
if (!result.$and) {
result.$and = []
}
result.$and.push({ [searchParam.path]: result[searchParam.path] })
result.$and.push({
[searchParam.path]: searchParam.value,
})
delete result[searchParam.path]
} else {
result[searchParam.path] = searchParam.value
}
}
} else if (typeof searchParam?.value === 'object') {
result = deepMergeWithCombinedArrays(result, searchParam.value ?? {}, {

View File

@@ -336,6 +336,41 @@ describe('Relationships', () => {
expect(query.docs).toHaveLength(1) // Due to limit: 1
})
it('should allow querying by relationships with an object where as AND', async () => {
const director = await payload.create({
collection: 'directors',
data: { name: 'Director1', localized: 'Director1_Localized' },
})
const movie = await payload.create({
collection: 'movies',
data: { director: director.id },
depth: 0,
})
const { docs: trueRes } = await payload.find({
collection: 'movies',
depth: 0,
where: {
'director.name': { equals: 'Director1' },
'director.localized': { equals: 'Director1_Localized' },
},
})
expect(trueRes).toStrictEqual([movie])
const { docs: falseRes } = await payload.find({
collection: 'movies',
depth: 0,
where: {
'director.name': { equals: 'Director1_Fake' },
'director.localized': { equals: 'Director1_Localized' },
},
})
expect(falseRes).toStrictEqual([])
})
it('should allow querying within blocks', async () => {
const rel = await payload.create({
collection: relationSlug,