diff --git a/packages/db-sqlite/src/countDistinct.ts b/packages/db-sqlite/src/countDistinct.ts index de0af7a995..ae729138f0 100644 --- a/packages/db-sqlite/src/countDistinct.ts +++ b/packages/db-sqlite/src/countDistinct.ts @@ -16,7 +16,7 @@ export const countDistinct: CountDistinct = async function countDistinct( }) .from(this.tables[tableName]) .where(where) - return Number(countResult[0]?.count) + return Number(countResult?.[0]?.count ?? 0) } let query: SQLiteSelect = db @@ -39,5 +39,5 @@ export const countDistinct: CountDistinct = async function countDistinct( // Instead, COUNT (GROUP BY id) can be used which is still slower than COUNT(*) but acceptable. const countResult = await query - return Number(countResult[0]?.count) + return Number(countResult?.[0]?.count ?? 0) } diff --git a/packages/drizzle/src/postgres/countDistinct.ts b/packages/drizzle/src/postgres/countDistinct.ts index 16c2f576c9..04d7559fcf 100644 --- a/packages/drizzle/src/postgres/countDistinct.ts +++ b/packages/drizzle/src/postgres/countDistinct.ts @@ -16,7 +16,8 @@ export const countDistinct: CountDistinct = async function countDistinct( }) .from(this.tables[tableName]) .where(where) - return Number(countResult[0].count) + + return Number(countResult?.[0]?.count ?? 0) } let query = db @@ -39,5 +40,5 @@ export const countDistinct: CountDistinct = async function countDistinct( // Instead, COUNT (GROUP BY id) can be used which is still slower than COUNT(*) but acceptable. const countResult = await query - return Number(countResult[0].count) + return Number(countResult?.[0]?.count ?? 0) } diff --git a/test/database/int.spec.ts b/test/database/int.spec.ts index f6ff086f6a..efad1d825d 100644 --- a/test/database/int.spec.ts +++ b/test/database/int.spec.ts @@ -2451,4 +2451,37 @@ describe('database', () => { expect(res.docs[0].id).toBe(customID.id) }) + + it('should count with a query that contains subqueries', async () => { + const category = await payload.create({ + collection: 'categories', + data: { title: 'new-category' }, + }) + const post = await payload.create({ + collection: 'posts', + data: { title: 'new-post', category: category.id }, + }) + + const result_1 = await payload.count({ + collection: 'posts', + where: { + 'category.title': { + equals: 'new-category', + }, + }, + }) + + expect(result_1.totalDocs).toBe(1) + + const result_2 = await payload.count({ + collection: 'posts', + where: { + 'category.title': { + equals: 'non-existing-category', + }, + }, + }) + + expect(result_2.totalDocs).toBe(0) + }) })