diff --git a/src/mongoose/buildQuery.ts b/src/mongoose/buildQuery.ts index ea87fa9f2d..b4d8fb7c1b 100644 --- a/src/mongoose/buildQuery.ts +++ b/src/mongoose/buildQuery.ts @@ -266,8 +266,10 @@ class ParamParser { if (collectionPathsToSearch.length === 1) return { path, value: { $in } }; + const nextSubPath = collectionPathsToSearch[i + 1].path; + return { - value: { _id: { $in } }, + value: { [nextSubPath]: { $in } }, }; } diff --git a/test/relationships/int.spec.ts b/test/relationships/int.spec.ts index e23c52b4ae..82864773ec 100644 --- a/test/relationships/int.spec.ts +++ b/test/relationships/int.spec.ts @@ -223,6 +223,89 @@ describe('Relationships', () => { }); }); }); + + describe('Nested Querying', () => { + let thirdLevelID: string; + let secondLevelID: string; + let firstLevelID: string; + + beforeAll(async () => { + const thirdLevelDoc = await payload.create({ + collection: 'chained-relation', + data: { + name: 'third', + }, + }); + + thirdLevelID = thirdLevelDoc.id; + + console.log({ thirdLevelID }); + + const secondLevelDoc = await payload.create({ + collection: 'chained-relation', + data: { + name: 'second', + relation: thirdLevelID, + }, + }); + + secondLevelID = secondLevelDoc.id; + + console.log({ secondLevelID }); + + const firstLevelDoc = await payload.create({ + collection: 'chained-relation', + data: { + name: 'first', + relation: secondLevelID, + }, + }); + + firstLevelID = firstLevelDoc.id; + + console.log({ firstLevelID }); + }); + + it('should allow querying one level deep', async () => { + const query1 = await payload.find({ + collection: 'chained-relation', + where: { + 'relation.name': { + equals: 'second', + }, + }, + }); + + expect(query1.docs).toHaveLength(1); + expect(query1.docs[0].id).toStrictEqual(firstLevelID); + + const query2 = await payload.find({ + collection: 'chained-relation', + where: { + 'relation.name': { + equals: 'third', + }, + }, + }); + + expect(query2.docs).toHaveLength(1); + expect(query2.docs[0].id).toStrictEqual(secondLevelID); + }); + + it('should allow querying two levels deep', async () => { + const query = await payload.find({ + collection: 'chained-relation', + where: { + 'relation.relation.name': { + equals: 'third', + }, + }, + }); + + expect(query.docs).toHaveLength(1); + expect(query.docs[0].id).toStrictEqual(firstLevelID); + }); + }); }); });