Tips for JSON Schema ValidationJSON架构验证提示
On this page本页内容
This page describes best practices for JSON schema validation to help avoid common issues.本页介绍JSON模式验证的最佳实践,以帮助避免常见问题。
_id
Field and 字段和additionalProperties: false
When you specify 当您在JSON模式中指定additionalProperties: false
in your JSON schema, MongoDB rejects documents that contain fields not included in your schema's properties
object.additionalProperties: false
时,MongoDB会拒绝包含未包含在模式的properties
对象中的字段的文档。
Because all objects contain an automatically-generated 因为所有对象都包含一个自动生成的_id
field, when you set additionalProperties: false
, you must include the _id
field in your properties
object. _id
字段,所以当您设置additionalProperties: false
时,必须在您的properties
对象中包含_id
字段。If you don't, all documents are rejected.如果不这样做,所有文档都将被拒绝。
For example, with this validation, no documents are valid:例如,通过此验证,没有任何文档是有效的:
{
"$jsonSchema": {
"required": [ "_id", "storeLocation" ],
"properties": {
"storeLocation": { "bsonType": "string" }
},
"additionalProperties": false
}
}
This validation ensures that 此验证确保storeLocation
is a string. storeLocation
是一个字符串。However, the 但是,properties
object does not contain an _id
field.properties
对象不包含_id
字段。
To allow documents in the collection, you must update the 若要允许集合中的文档,必须更新properties
object to include an _id
field:properties
对象以包含_id
字段:
{
"$jsonSchema": {
"required": [ "_id", "storeLocation" ],
"properties": {
"_id": { "bsonType": "objectId" },
"storeLocation": { "bsonType": "string" }
},
"additionalProperties": false
}
}
Validation for null
Field Values验证null
字段值
null
Field ValuesYour application may be configured to set missing field values to 您的应用程序可能被配置为将缺少的字段值设置为null
, instead of not including those fields in the object sent to the collection.null
,而不是在发送到集合的对象中不包括这些字段。
If your schema validates data types for a field, to insert documents with a 如果架构验证某个字段的数据类型,则要插入该字段具有null
value for that field, you must explicitly allow null
as a valid BSON type.null
值的文档,必须明确允许null
作为有效的BSON类型。
For example, this schema validation does not allow documents where 例如,此架构验证不允许storeLocation
is null
:storeLocation
为null
的文档:
db.createCollection("sales",
{
validator:
{
"$jsonSchema": {
"properties": {
"storeLocation": { "bsonType": "string" }
}
}
}
}
)
With the preceding validation, this document is rejected:通过上述验证,本文件被拒绝:
db.store.insertOne( { storeLocation: null } )
Alternatively, this schema validation allows 或者,此架构验证允许null
values for storeLocation
:storeLocation
为null
值:
db.createCollection("store",
{
validator:
{
"$jsonSchema": {
"properties": {
"storeLocation": { "bsonType": [ "null", "string" ] }
}
}
}
}
)
With the preceding validation, this document is allowed:通过上述验证,本文档可以:
db.store.insertOne( { storeLocation: null } )
null Fields Compared with Missing Fieldsnull
字段与缺失字段的比较
null
field values are not the same as missing fields. 字段值与缺少的字段不同。If a field is missing from a document, MongoDB does not validate that field.如果文档中缺少字段,MongoDB不会验证该字段。