使用PyMongo创建MongoDB验证器时遭遇TypeMismatch错误求助
解决MongoDB集合验证器解析错误问题
问题原因
你写的$jsonSchema里存在层级错误的description字段,导致MongoDB解析验证器时出错。具体是在rules字段的定义末尾,多写了几个位置完全错误的description——这些description没有嵌套在正确的属性定义对象里,MongoDB会把它们当成新的属性schema解析,但它们的值是字符串而非合法的schema对象,因此触发了TypeMismatch错误。
修正后的验证器代码
user_validator = { "$jsonSchema": { "bsonType": "object", "required": ["user_email", "user_name", "rules"], "description": "用户文档必须包含user_email、user_name和rules字段", "properties": { "user_email": { "bsonType": "string", "description": "必须是字符串,且为必填项" }, "user_name": { "bsonType": "string", "description": "必须是字符串,且为必填项" }, "rules": { "bsonType": "array", "description": "必须是对象数组,且为必填项", "items": { "bsonType": "object", "description": "数组中的每个元素必须是对象", "properties": { "name": { "bsonType": "string", "description": "必须是字符串" }, "commit_hashes": { "bsonType": "array", "description": "必须是对象数组", "items": { "bsonType": "object", "description": "数组中的每个元素必须是包含hash和date的对象", "properties": { "hash": { "bsonType": "string", "description": "必须是字符串" }, "date": { "bsonType": "string", "description": "必须是字符串" } } } } } } } } } }
关键修正点
- 移除了所有位置错误的
description字段,确保每个description都嵌套在对应的属性schema对象内部 - 调整了括号层级,保证整个JSON结构合法
- 保留所有必要验证规则,同时让每个描述对应正确的字段
内容的提问来源于stack exchange,提问作者wondergrandma
相关产品推荐
相关产品推荐

