# MongoServerError：文档验证失败：不允许额外属性：'extraField'

- **ID:** `mongodb/schema-validation-type-error`
- **领域:** mongodb
- **类别:** data_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 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 | — | — |

## 解决方案

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' })
   ```

## 无效尝试

- **** — This removes all data and validation, which is destructive and not a fix for the schema mismatch. (100% 失败率)
- **** — This bypasses validation entirely, defeating the purpose of schema enforcement. (70% 失败率)
- **** — The document will always fail validation unless it is modified. (100% 失败率)
