Docs Home → Develop Applications → MongoDB Manual
On this page本页内容
This page describes best practices for JSON schema validation to help avoid common issues.本页描述了JSON模式验证的最佳实践,以帮助避免常见问题。
_id
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 fornull
Field Valuesnull
字段值的验证
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 allownull
as a valid BSON type.null
值的文档,必须明确允许null
值作为有效的BSON类型。
For example, this schema validation does not allow documents where例如,此架构验证不允许storeLocation
isnull
: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 forstoreLocation
: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 } )Note注意
null Fields Compared with Missing Fields空字段与缺失字段比较
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不会验证该字段。