【发布时间】:2019-11-20 10:18:51
【问题描述】:
我创建了一个具有以下验证的集合:
{
$jsonSchema: {
bsonType: 'object',
additionalProperties: false,
properties: {
_id: {
bsonType: 'objectId'
},
test: {
bsonType: 'string'
}
},
anyOf: [
{
bsonType: 'object',
properties: {
test1: {
bsonType: 'string'
}
},
additionalProperties: false
},
{
bsonType: 'object',
properties: {
test2: {
bsonType: 'string'
}
},
additionalProperties: false
}
]
}
}
验证操作设置为错误,验证级别设置为中等。
当我尝试插入包含字段 test 和 test1 的文档时,我收到验证错误
Document:
db.dmt9.insert([{test:"123"},{test1:"456"}])
Error:
BulkWriteResult({
"writeErrors" : [
{
"index" : 0,
"code" : 121,
"errmsg" : "Document failed validation",
"op" : {
"_id" : ObjectId("5dd511de1f7b2047ed527044"),
"test" : "123"
}
}
],
"writeConcernErrors" : [ ],
"nInserted" : 0,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
既然我要插入一个包含 AnyOf 中的一个字段的文档,那么该文档不应该被成功插入吗?如果我尝试将验证操作更改为警告,则会插入文档,但我可以插入任何其他字段。
Test with validation Action - Warning
rs0:PRIMARY> db.dmt9.insert([{test:"123"},{test1:"456"},{test9:123}])
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 3,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
更新 2: 当我删除现场测试时,我得到了这个验证器:
{
$jsonSchema: {
bsonType: 'object',
additionalProperties: false,
anyOf: [
{
bsonType: 'object',
properties: {
test1: {
bsonType: 'string'
}
},
additionalProperties: false
},
{
bsonType: 'object',
properties: {
test2: {
bsonType: 'string'
}
},
additionalProperties: false
}
],
properties: {
_id: {
bsonType: 'objectId'
}
}
}
}
当我再次尝试插入 test1 时,我仍然收到错误消息文档验证失败
rs0:PRIMARY> db.dmt8.insert([{test1:"123"}])
BulkWriteResult({
"writeErrors" : [
{
"index" : 0,
"code" : 121,
"errmsg" : "Document failed validation",
"op" : {
"_id" : ObjectId("5dd51b4766ba25a01fbcf8e6"),
"test1" : "123"
}
}
],
"writeConcernErrors" : [ ],
"nInserted" : 0,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
【问题讨论】:
-
你认为
anyOf应该怎么做? -
我希望 anyof 允许我插入包含“test1”或“test2”字段的文档
标签: mongodb jsonschema json-schema-validator