Docs HomeMongoDB Manual

Tips for JSON Schema ValidationJSON架构验证提示

This page describes best practices for JSON schema validation to help avoid common issues.本页介绍JSON模式验证的最佳实践,以帮助避免常见问题。

_id Field and 字段和additionalProperties: false

When you specify additionalProperties: false in your JSON schema, MongoDB rejects documents that contain fields not included in your schema's properties object.当您在JSON模式中指定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字段值

Your 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:例如,此架构验证不允许storeLocationnull的文档:

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:或者,此架构验证允许storeLocationnull值:

db.createCollection("store",
{
validator:
{
"$jsonSchema": {
"properties": {
"storeLocation": { "bsonType": [ "null", "string" ] }
}
}
}
}
)

With the preceding validation, this document is allowed:通过上述验证,本文档可以:

db.store.insertOne( { storeLocation: null } )
Note

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不会验证该字段。