MongoDB集合插入记录失败:文档验证错误排查求助
MongoDB集合Schema验证失败无法插入记录的解决方案
问题概述
创建带Schema验证的fiction集合后,插入记录始终失败,已尝试重启服务器、删除重建集合、检查拼写等操作,问题仍未解决。
环境信息
- MongoDB版本:7.0.0
- 系统:Ubuntu 22.04 LTS
- Shell:Mongosh
原集合Schema(错误写法)
db.createCollection("fiction", { validator: { required: ['name', 'price', 'authors'], properties: { name: { bsonType: 'string', description: 'must be a String and required' }, price: { bsonType: 'number', description: 'must be a number and required' }, authors: { bsonType: 'array', description: 'must be an array and required', items: { bsonType: 'object', properties: { name: { bsonType: 'string' }, email: { bsonType: 'string' } } } } } }, validationAction: 'error' })
插入代码示例
// 注:原代码误插入到nonfiction集合,后续修正为插入fiction仍报错 db.fiction.insertOne({ name: "Sample Fiction Book", price: 19.99, authors: [ { name: "Author Name", email: "author@email.com" }, { name: "Co-Author Name", email: "coauthor@email.com" } ] })
错误信息
Uncaught: MongoServerError: Document failed validation Additional information: { failingDocumentId: ObjectId("64f719e6f13ccec17a71558e"), details: { operatorName: '$and', clausesNotSatisfied: [ { index: 0, details: { operatorName: '$eq', specifiedAs: { required: [ 'name', 'price', 'authors' ] }, reason: 'field was missing' } }, { index: 1, details: { operatorName: '$eq', specifiedAs: { properties: { name: [Object], price: [Object], authors: [Object] } }, reason: 'field was missing' } } ] } }
问题原因
MongoDB的文档验证器要求使用**$jsonSchema关键字**包裹JSON Schema定义,原代码直接将required和properties放在validator对象中,MongoDB会将其视为普通查询条件(而非JSON Schema规则),导致验证逻辑错误,误判文档缺少required和properties字段。
正确解决方案
修改集合创建代码,用$jsonSchema包裹Schema规则:
db.createCollection("fiction", { validator: { $jsonSchema: { // 新增$jsonSchema关键字,明确指定为JSON Schema验证 required: ['name', 'price', 'authors'], properties: { name: { bsonType: 'string', description: '必须为字符串且为必填项' }, price: { bsonType: 'number', description: '必须为数字且为必填项' }, authors: { bsonType: 'array', description: '必须为数组且为必填项', items: { bsonType: 'object', properties: { name: { bsonType: 'string' }, email: { bsonType: 'string' } } } } } } }, validationAction: 'error' })
验证修复效果
重新创建集合后执行插入代码,会返回成功结果:
{ acknowledged: true, insertedId: ObjectId("...") // 实际生成的ObjectId }
内容的提问来源于stack exchange,提问作者Shrey Tandel
相关产品推荐
相关产品推荐

