{"record":{"id":"6d33ebeb0c961d39","repo":"pubkey/rxdb","slug":"vd2","errorCode":"VD2","errorMessage":"\n        RxDB Error-Code: ${message}.\n        Hint: Error messages are not included in RxDB core to reduce build size.\n        To show the full error messages and to ensure that you do not make any mistakes when using RxDB,\n        use the dev-mode plugin when you are in development mode: https://rxdb.info/dev-mode.html?console=error\n        \nFind out more about this error here: https://rxdb.info/errors.html?console=errors#VD2 \nStill stuck? Ask in the RxDB Discord: https://rxdb.info/chat \n","messagePattern":"\n        RxDB Error-Code: (.+?)\\.\n        Hint: Error messages are not included in RxDB core to reduce build size\\.\n        To show the full error messages and to ensure that you do not make any mistakes when using RxDB,\n        use the dev-mode plugin when you are in development mode: https://rxdb\\.info/dev-mode\\.html\\?console=error\n        \nFind out more about this error here: https://rxdb\\.info/errors\\.html\\?console=errors#VD2 \nStill stuck\\? Ask in the RxDB Discord: https://rxdb\\.info/chat \n","errorType":"error_code","errorClass":"RxError","httpStatus":422,"severity":"error","filePath":"src/rx-storage-helper.ts","lineNumber":174,"sourceCode":"    );\n}\n\nexport function throwIfIsStorageWriteError<RxDocType>(\n    collection: RxCollection<RxDocType, any, any>,\n    documentId: string,\n    writeData: RxDocumentWriteData<RxDocType> | RxDocType,\n    error: RxStorageWriteError<RxDocType> | undefined\n) {\n    if (error) {\n        if (error.status === 409) {\n            throw newRxError('CONFLICT', {\n                collection: collection.name,\n                id: documentId,\n                writeError: error,\n                data: writeData\n            });\n        } else if (error.status === 422) {\n            throw newRxError('VD2', {\n                collection: collection.name,\n                id: documentId,\n                writeError: error,\n                data: writeData\n            });\n        } else {\n            throw error;\n        }\n    }\n}\n\n\n/**\n * Use a counter-based event bulk ID instead of randomToken()\n * for better performance. The prefix ensures uniqueness across instances.\n */\nconst EVENT_BULK_ID_PREFIX = randomToken(10);\nlet eventBulkCounter = 0;","sourceCodeStart":156,"sourceCodeEnd":192,"githubUrl":"https://github.com/pubkey/rxdb/blob/af6fb65f94cd70558d74c23799eda11ff1c15224/src/rx-storage-helper.ts#L156-L192","documentation":"VD2 (VD = validation) is thrown by throwIfIsStorageWriteError in src/rx-storage-helper.ts:174 when an underlying RxStorage write operation rejects a document with HTTP-style status 422, meaning the document failed the RxJSONSchema validation. RxDB validates every write against the collection schema at the storage layer; instead of writing invalid data it surfaces this error. The 409 case is routed to the CONFLICT error, everything else passes through, so VD2 specifically means 'the document shape violates the schema'.","triggerScenarios":"Calling insert(), upsert(), _saveData() (used by incrementalModify/save), or remove() on an RxCollection where the written document violates the collection's RxJsonSchema: missing required fields, wrong types, additionalProperties: true violations, maxLength exceeded on the primary key, or invalid attachment metadata. throwIfIsStorageWriteError is also called by replication and migration code paths when they pipe writes through the collection.","commonSituations":"Writing documents whose primary key (string type) exceeds its declared maxLength; forgetting required fields when constructing documents manually; migrating code between schema versions and writing docs in the old shape; receiving JSON from a server or user input that is not normalized before insert; using upsert() with a partial document instead of a full document.","solutions":["Log err.parameters.writeError and err.parameters.data (the RxError carries them) to see exactly which schema keyword failed and for which document id.","Temporarily add the dev-mode plugin in development to get the full human-readable error message instead of the error code.","Fix the document so it matches the collection schema (required fields, types, primary key maxLength), then retry the write.","If writing partial data, fetch the existing document first and merge, or use incrementalUpsert()/modify() instead of upsert().","If the schema itself is wrong for your data (e.g. maxLength: 100 is too small for your ids), bump the schema (new collection/version + migration) rather than writing invalid data."],"exampleFix":"// before: partial doc fails 422 validation\nawait collection.upsert({ id: 'foo', name: 'x' }); // VD2: missing required 'age'\n\n// after: full valid document matching the schema\nawait collection.upsert({ id: 'foo', name: 'x', age: 42 });","handlingStrategy":"validation","validationCode":"// validate a candidate document against the collection schema before writing\nfunction validateAgainstSchema(doc, rxSchema) {\n  const errors = rxSchema.validate(doc); // returns list of schema errors\n  if (errors.length > 0) {\n    throw new Error('Invalid document: ' + JSON.stringify(errors));\n  }\n}\n\n// simpler checks before insert/upsert\nconst pk = collection.schema.primaryPath;\nif (typeof doc[pk] !== 'string' || doc[pk].length > collection.schema.getSchemaOfMainPath()[pk].maxLength) {\n  throw new Error('Primary key missing or exceeds maxLength');\n}","typeGuard":null,"tryCatchPattern":"try {\n  await collection.insert(doc);\n} catch (err) {\n  if (err && err.code === 'VD2') {\n    console.error('Schema validation failed for id', err.parameters.id);\n    console.error(JSON.stringify(err.parameters.writeError, null, 2));\n    console.error('Data was:', JSON.stringify(err.parameters.data, null, 2));\n    return; // handle invalid data explicitly\n  }\n  throw err;\n}","preventionTips":["Run with the dev-mode plugin in development so validation errors show full messages immediately.","Keep a single factory function that constructs documents so every write goes through the same shape check.","Always write complete documents via insert()/upsert(); use incrementalUpsert() or modify() for partial updates.","Size the primary key maxLength generously and validate user-supplied ids before inserting.","Add unit tests that insert representative documents through the real collection before shipping."],"tags":["schema","validation","write"],"backgroundTag":"schema-validation-failed","analyzedSha":"af6fb65f94cd70558d74c23799eda11ff1c15224","analyzedAt":"2026-08-31T23:32:37.842Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-08T05:18:18.240Z"}