diff --git a/src/runtime/query/match/utils.ts b/src/runtime/query/match/utils.ts index 58b12f9a9..6a0d12724 100644 --- a/src/runtime/query/match/utils.ts +++ b/src/runtime/query/match/utils.ts @@ -67,9 +67,18 @@ export const sortList = (data: any[], params: SortOptions) => { for (const key of keys) { data = data.sort((a, b) => { const values = [get(a, key), get(b, key)] - // `null` values are treated as `"null"` strings and ordered alphabetically - // Turn `null` values into `undefined` so they place at the end of the list - .map(value => value === null ? undefined : value) + .map((value) => { + // `null` values are treated as `"null"` strings and ordered alphabetically + // Turn `null` values into `undefined` so they place at the end of the list + if (value === null) { + return undefined + } + // Convert Date object to ISO string + if (value instanceof Date) { + return value.toISOString() + } + return value + }) if (params[key] === -1) { values.reverse() } diff --git a/test/features/query/query.test.ts b/test/features/query/query.test.ts index edfd9968e..02476a902 100644 --- a/test/features/query/query.test.ts +++ b/test/features/query/query.test.ts @@ -75,6 +75,28 @@ describe('Database Provider', () => { }) }) + test('Apply sort Date', async () => { + const dates = [ + { date: new Date('2022-01-01 00:00:00.001Z') }, + { date: new Date('2021-01-01 00:00:00.001Z') }, + { date: new Date('2020-01-01 00:00:00.001Z') }, + { date: new Date('2019-01-01 00:00:00.001Z') }, + { date: new Date('2018-01-01 00:00:00.001Z') }, + { date: new Date('1900-01-01 00:00:00.001Z') } + ] + const fetcher = createPipelineFetcher(() => Promise.resolve(dates.sort(() => 1 - Math.random()))) + + const sortedByDate1 = await createQuery(fetcher).sort({ date: 1 }).find() + ;([...dates].reverse()).forEach(({ date }, index) => { + expect(sortedByDate1[index].date).toBe(date) + }) + + const sortedByDate0 = await createQuery(fetcher).sort({ date: -1 }).find() + dates.forEach(({ date }, index) => { + expect(sortedByDate0[index].date).toBe(date) + }) + }) + test('Apply sort $numeric', async () => { // sort string alphabetically const nonNumericSort = await createQuery(pipelineFetcher).sort({ numberString: 1 }).find()