From faab09b76fca902f313899b308f0382c38911cfd Mon Sep 17 00:00:00 2001 From: James Date: Mon, 9 Jan 2023 19:41:30 -0500 Subject: [PATCH] chore: ensures sort is used within mergeDrafts --- src/versions/drafts/mergeDrafts.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/versions/drafts/mergeDrafts.ts b/src/versions/drafts/mergeDrafts.ts index a52e624071..9d7a9832f7 100644 --- a/src/versions/drafts/mergeDrafts.ts +++ b/src/versions/drafts/mergeDrafts.ts @@ -44,7 +44,7 @@ export const mergeDrafts = async ({ }: Args): Promise> => { // Query the main collection for any IDs that match the query // Create object "map" for performant lookup - const mainCollectionMatchMap = await collection.Model.find(query, { updatedAt: 1 }, { limit: paginationOptions.limit }) + const mainCollectionMatchMap = await collection.Model.find(query, { updatedAt: 1 }, { limit: paginationOptions.limit, sort: paginationOptions.sort }) .lean().then((res) => res.reduce((map, { _id, updatedAt }) => { const newMap = map; newMap[_id] = updatedAt; @@ -83,7 +83,15 @@ export const mergeDrafts = async ({ // This means that the newer version's parent should appear in the main query. // To do so, add the version's parent ID into an explicit `includedIDs` array const versionCollectionMatchMap = await VersionModel.aggregate>([ - { $sort: { updatedAt: -1 } }, + { + $sort: Object.entries(paginationOptions.sort).reduce((sort, [key, order]) => { + return { + ...sort, + [key]: order === 'asc' ? 1 : -1, + }; + }, {}), + }, + { $match: versionQuery }, { $group: { _id: '$parent', @@ -93,7 +101,6 @@ export const mergeDrafts = async ({ createdAt: { $first: '$createdAt' }, }, }, - { $match: versionQuery }, { $limit: paginationOptions.limit }, ]).then((res) => res.reduce>((map, { _id, updatedAt, createdAt, version }) => { const newMap = map;