diff --git a/packages/payload/src/config/orderable/index.ts b/packages/payload/src/config/orderable/index.ts index 742f3e4fd..f79d500dd 100644 --- a/packages/payload/src/config/orderable/index.ts +++ b/packages/payload/src/config/orderable/index.ts @@ -106,24 +106,27 @@ export const addOrderableFieldsAndHook = ( collection.hooks.beforeChange = [] } - const orderBeforeChangeHook: BeforeChangeHook = async ({ data, operation, req }) => { - // Only set _order on create, not on update (unless explicitly provided) - if (operation === 'create') { - for (const orderableFieldName of orderableFieldNames) { - if (!data[orderableFieldName]) { - const lastDoc = await req.payload.find({ - collection: collection.slug, - depth: 0, - limit: 1, - pagination: false, - req, - select: { [orderableFieldName]: true }, - sort: `-${orderableFieldName}`, - }) + const orderBeforeChangeHook: BeforeChangeHook = async ({ data, originalDoc, req }) => { + for (const orderableFieldName of orderableFieldNames) { + if (!data[orderableFieldName] && !originalDoc?.[orderableFieldName]) { + console.log('do not enter') + const lastDoc = await req.payload.find({ + collection: collection.slug, + depth: 0, + limit: 1, + pagination: false, + req, + select: { [orderableFieldName]: true }, + sort: `-${orderableFieldName}`, + where: { + [orderableFieldName]: { + exists: true, + }, + }, + }) - const lastOrderValue = lastDoc.docs[0]?.[orderableFieldName] || null - data[orderableFieldName] = generateKeyBetween(lastOrderValue, null) - } + const lastOrderValue = lastDoc.docs[0]?.[orderableFieldName] || null + data[orderableFieldName] = generateKeyBetween(lastOrderValue, null) } } @@ -163,7 +166,7 @@ export const addOrderableEndpoint = (config: SanitizedConfig) => { } if ( typeof target !== 'object' || - typeof target.id !== 'string' || + typeof target.id === 'undefined' || typeof target.key !== 'string' ) { return new Response(JSON.stringify({ error: 'target must be an object with id and key' }), {