fix(db-mongodb): sort by fields in relationships with draft: true (#12387)

Fixes sorting by fields in relationships, e.g `sort: "author.name"` when
using `draft: true`. The existing test that includes check with `draft:
true` was accidentally passing because it used to sort by the
relationship field itself.
This commit is contained in:
Sasha
2025-05-12 22:35:16 +03:00
committed by GitHub
parent 8219c046de
commit fd67d461ac
3 changed files with 20 additions and 19 deletions

View File

@@ -57,12 +57,8 @@ const relationshipSort = ({
return false
}
for (const [i, segment] of segments.entries()) {
if (versions && i === 0 && segment === 'version') {
segments.shift()
continue
}
for (let i = 0; i < segments.length; i++) {
const segment = segments[i]
const field = currentFields.find((each) => each.name === segment)
if (!field) {
@@ -71,6 +67,10 @@ const relationshipSort = ({
if ('fields' in field) {
currentFields = field.flattenedFields
if (field.name === 'version' && versions && i === 0) {
segments.shift()
i--
}
} else if (
(field.type === 'relationship' || field.type === 'upload') &&
i !== segments.length - 1
@@ -106,7 +106,7 @@ const relationshipSort = ({
as: `__${path}`,
foreignField: '_id',
from: foreignCollection.Model.collection.name,
localField: relationshipPath,
localField: versions ? `version.${relationshipPath}` : relationshipPath,
pipeline: [
{
$project: {

View File

@@ -151,6 +151,7 @@ export const queryDrafts: QueryDrafts = async function queryDrafts(
query: versionQuery,
session: paginationOptions.options?.session ?? undefined,
sort: paginationOptions.sort as object,
sortAggregation,
useEstimatedCount: paginationOptions.useEstimatedCount,
})
} else {

View File

@@ -670,18 +670,6 @@ describe('Relationships', () => {
await payload.delete({ collection: 'directors', where: {} })
await payload.delete({ collection: 'movies', where: {} })
const director_1 = await payload.create({
collection: 'directors',
data: { name: 'Dan', localized: 'Dan' },
})
await payload.update({
collection: 'directors',
id: director_1.id,
locale: 'de',
data: { localized: 'Mr. Dan' },
})
const director_2 = await payload.create({
collection: 'directors',
data: { name: 'Mr. Dan', localized: 'Mr. Dan' },
@@ -694,6 +682,18 @@ describe('Relationships', () => {
data: { localized: 'Dan' },
})
const director_1 = await payload.create({
collection: 'directors',
data: { name: 'Dan', localized: 'Dan' },
})
await payload.update({
collection: 'directors',
id: director_1.id,
locale: 'de',
data: { localized: 'Mr. Dan' },
})
const movie_1 = await payload.create({
collection: 'movies',
depth: 0,