Skip to content

fix(db-mongodb): handle admin.condition in sparse unique indexes#16648

Open
rachit367 wants to merge 1 commit into
payloadcms:mainfrom
rachit367:fix-conditional-sparse-index
Open

fix(db-mongodb): handle admin.condition in sparse unique indexes#16648
rachit367 wants to merge 1 commit into
payloadcms:mainfrom
rachit367:fix-conditional-sparse-index

Conversation

@rachit367
Copy link
Copy Markdown

What?

formatBaseSchema in packages/db-mongodb/src/models/buildSchema.ts decides whether a unique index should be sparse by checking the static field.required property. A field with required: true always gets a non-sparse unique index, even when admin.condition makes it only conditionally required.

This change treats a field as effectively optional for index purposes whenever required: true is combined with an admin.condition, so a sparse unique index is created and documents that omit the field do not collide on null.

Why?

Fixes #16298.

Today, the following field definition creates a non-sparse unique index:

{
  name: 'slug',
  type: 'text',
  unique: true,
  required: true,
  admin: {
    condition: (data) => data.type === 'page',
  },
}

Two documents where type !== 'page' both leave slug as null, and the second insert fails with a Mongo unique constraint violation because the index treats both nulls as duplicates.

How?

buildSchema.ts:

  • Introduce effectivelyOptional = field.required !== true || Boolean(field.admin?.condition).
  • Use it in place of the existing field.required !== true check inside the sparse-index branch.

No behavior change for fields without admin.condition — the expression collapses to the original check. Fields that are conditionally required now get sparse: true, matching what already happens for required: false, localized, or drafts-enabled fields.

Scope is limited to @payloadcms/db-mongodb since the issue is reported against the Mongo index builder; other adapters are not touched.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[db:mongodb] Non-sparse unique index created for conditionally required fields

1 participant