mongodb data_error ai_generated true

MongoServerError: Document failed validation: Additional properties not allowed: 'extraField'

ID: mongodb/schema-validation-type-error

Also available as: JSON · Markdown · 中文
90%Fix Rate
85%Confidence
1Evidence
2023-11-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
mongodb-3.6 active
mongodb-4.0 active
mongodb-4.2 active
mongodb-4.4 active
mongodb-5.0 active
mongodb-6.0 active
mongodb-7.0 active

Root Cause

A document being inserted or updated violates the collection's JSON Schema validator that has additionalProperties set to false.

generic

中文

插入或更新的文档违反了集合的 JSON Schema 验证器,该验证器将 additionalProperties 设置为 false。

Official Documentation

https://www.mongodb.com/docs/manual/core/schema-validation/

Workarounds

  1. 90% success Modify the document to remove the extra field before insertion. Example in Node.js: delete doc.extraField; await collection.insertOne(doc);
    Modify the document to remove the extra field before insertion. Example in Node.js: delete doc.extraField; await collection.insertOne(doc);
  2. 85% success Update the collection validator to allow the extra field: db.runCommand({ collMod: 'mycollection', validator: { $jsonSchema: { bsonType: 'object', additionalProperties: true, properties: { extraField: { bsonType: 'string' } } } } })
    Update the collection validator to allow the extra field: db.runCommand({ collMod: 'mycollection', validator: { $jsonSchema: { bsonType: 'object', additionalProperties: true, properties: { extraField: { bsonType: 'string' } } } } })
  3. 80% success Use validationAction: 'warn' instead of 'error' to log violations without blocking writes: db.runCommand({ collMod: 'mycollection', validationAction: 'warn' })
    Use validationAction: 'warn' instead of 'error' to log violations without blocking writes: db.runCommand({ collMod: 'mycollection', validationAction: 'warn' })

中文步骤

  1. Modify the document to remove the extra field before insertion. Example in Node.js: delete doc.extraField; await collection.insertOne(doc);
  2. Update the collection validator to allow the extra field: db.runCommand({ collMod: 'mycollection', validator: { $jsonSchema: { bsonType: 'object', additionalProperties: true, properties: { extraField: { bsonType: 'string' } } } } })
  3. Use validationAction: 'warn' instead of 'error' to log violations without blocking writes: db.runCommand({ collMod: 'mycollection', validationAction: 'warn' })

Dead Ends

Common approaches that don't work:

  1. 100% fail

    This removes all data and validation, which is destructive and not a fix for the schema mismatch.

  2. 70% fail

    This bypasses validation entirely, defeating the purpose of schema enforcement.

  3. 100% fail

    The document will always fail validation unless it is modified.