{"record":{"id":"e3b34ed8f6a163f0","repo":"payloadcms/payload","slug":"value-must-be-unique","errorCode":null,"errorMessage":"Value must be unique","messagePattern":"Value must be unique","errorType":"validation","errorClass":"ValidationError","httpStatus":400,"severity":"error","filePath":"packages/db-mongodb/src/utilities/handleError.ts","lineNumber":66,"sourceCode":"  if (!error || typeof error !== 'object') {\n    throw error\n  }\n\n  // Handle uniqueness error from MongoDB\n  if ('code' in error && error.code === 11000) {\n    let path: null | string = null\n\n    if ('keyValue' in error && error.keyValue && typeof error.keyValue === 'object') {\n      path = Object.keys(error.keyValue)[0] ?? ''\n    } else if ('message' in error && typeof error.message === 'string') {\n      path = extractFieldFromMessage(error.message)\n    }\n\n    if (path) {\n      path = stripLocaleFromPath(path, req)\n    }\n\n    throw new ValidationError(\n      {\n        collection,\n        errors: [\n          {\n            message: req?.t ? req.t('error:valueMustBeUnique') : 'Value must be unique',\n            path: path ?? '',\n          },\n        ],\n        global,\n      },\n      req?.t,\n    )\n  }\n\n  // eslint-disable-next-line @typescript-eslint/only-throw-error\n  throw error\n}\n","sourceCodeStart":48,"sourceCodeEnd":84,"githubUrl":"https://github.com/payloadcms/payload/blob/00c58b35c0ed348ddc22daabf467b139727214fd/packages/db-mongodb/src/utilities/handleError.ts#L48-L84","documentation":"Thrown as a structured `ValidationError` by `handleError` when MongoDB returns a duplicate-key error (E11000). The handler extracts the offending field from `error.keyValue` (or parses the message), strips any locale suffix from the path, and re-throws a per-field validation error so the API responds with a clean validation failure instead of a 500. The message resolves to `req.t('error:valueMustBeUnique')` when a translator is present, else the literal 'Value must be unique'.","triggerScenarios":"A `create` or `update` (or REST POST/PATCH) sets a field that carries a unique index to a value that already exists in the collection. The unique constraint can come from `unique: true` on a field or a manually-created unique index.","commonSituations":"Unique field collision on email/username/slug; seeding duplicate data; a race where two concurrent writes pick the same value; a previously-deleted doc whose unique value was retained by a soft-delete or a stale index.","solutions":["Choose a different value for the flagged field (path is in the error).","Pre-check uniqueness before writing when contention is likely.","Remove the `unique: true` flag or the underlying unique index if duplicates are acceptable.","Surface the ValidationError to the UI and prompt the user to change the value."],"exampleFix":"// before\nawait payload.create({ collection: 'users', data: { email: 'taken@x.com' } })\n// after\nconst exists = await payload.find({ collection: 'users', where: { email: { equals: 'taken@x.com' } }, limit: 1 })\nif (exists.docs.length) throw new Error('email taken')\nawait payload.create({ collection: 'users', data: { email: 'new@x.com' } })","handlingStrategy":"try-catch","validationCode":"async function assertUnique(payload, collection, field, value) {\n  const { docs } = await payload.find({ collection, where: { [field]: { equals: value } }, limit: 1 })\n  if (docs.length) throw new Error(`${field} already in use`)\n}","typeGuard":"const isValidationError = (e) =>\n  e?.name === 'ValidationError' && Array.isArray(e.data?.errors)","tryCatchPattern":"try { await payload.create({ collection, data }) }\ncatch (e) {\n  if (isValidationError(e) && e.data.errors.some(x => /unique/i.test(x.message))) {\n    return { ok: false, field: e.data.errors[0].path }\n  }\n  throw e\n}","preventionTips":["Pre-check uniqueness for high-contention unique fields before writing.","Catch ValidationError at the API boundary and map path -> user message.","Avoid seeding duplicate values for unique-indexed fields.","Re-evaluate whether `unique: true` is needed if duplicates are acceptable."],"tags":["mongodb","unique","validation","duplicate-key"],"backgroundTag":null,"analyzedSha":"00c58b35c0ed348ddc22daabf467b139727214fd","analyzedAt":"2026-08-12T20:45:03.758Z","schemaVersion":2},"datasetVersion":"2026-08-12T23:17:12.415Z"}