能否在MongoDB验证Schema中添加不影响校验的可查询属性?
可以在MongoDB验证器中添加不影响校验的属性
完全可以实现这个需求,有两种常用方式:
方式1:在Schema的properties中明确定义属性(推荐)
直接在现有properties里添加你需要的属性,不设置任何校验规则(或仅设置允许任意类型),插入文档时MongoDB不会对这个属性做校验,但你可以正常查询获取它。
比如你需要添加formMetadata来存储表单生成的额外信息,修改后的Schema如下:
{ $jsonSchema: { bsonType: 'object', required: [ 'active', 'productive', 'translation', 'code' ], properties: { code: { bsonType: 'string', minLength: 0, maxLength: 50, }, active: { bsonType: 'bool' }, productive: { bsonType: 'bool' }, translation: { bsonType: 'object', properties: { 'pt-BR': { bsonType: 'object', required: [ 'description' ], properties: { description: { bsonType: 'string', minLength: 0, maxLength: 50 } } }, 'en-US': { bsonType: 'object', required: [ 'description' ], properties: { description: { bsonType: 'string', minLength: 0, maxLength: 50 } } } } }, audit: { bsonType: 'object', required: [ 'user' ], properties: { user: { bsonType: 'string' } } }, // 新增的不校验属性 formMetadata: { bsonType: 'mixed' // 允许任意类型的值,也可以留空对象{} } } } }
这种方式的好处是Schema里明确标注了属性存在,后续维护和查询时更清晰,符合你用Schema动态生成表单的需求。
方式2:启用additionalProperties允许任意未定义属性
如果不想在Schema里明确写出属性,可以设置additionalProperties: true,这样所有未在properties里定义的属性都能被插入,且不触发校验:
{ $jsonSchema: { bsonType: 'object', required: [ 'active', 'productive', 'translation', 'code' ], additionalProperties: true, // 新增这一行 properties: { // 原有属性保持不变... } } }
不过这种方式无法从Schema里直观看到你需要的额外属性,不利于后续维护,所以更推荐第一种方式。
原理说明
MongoDB的JSON Schema验证只会校验:
required数组中指定的必填属性是否存在properties中定义了校验规则的属性是否符合规则
只要某个属性没有被设置校验规则(或规则允许任意值),插入时就不会因为这个属性导致验证失败,同时该属性会被正常存储,后续可以通过查询获取。
内容的提问来源于stack exchange,提问作者Brayan Vinicius Jordan
相关产品推荐
相关产品推荐

