Database Manual / Data Modeling / Schema Validation

Specify Validation Level for Existing Documents指定现有文档的验证级别

For documents that already exist in your collection prior to adding validation, you can specify how MongoDB applies validation rules to these documents.对于在添加验证之前已经存在于集合中的文档,您可以指定MongoDB如何将验证规则应用于这些文档。

Context上下文

Your schema's validationLevel determines the documents for which MongoDB applies validation rules:模式的validationLevel决定了MongoDB应用验证规则的文档:

Validation Level验证级别Behavior
strict(Default) MongoDB applies the same validation rules to all document inserts and updates.MongoDB对所有文档插入和更新应用相同的验证规则。
moderateMongoDB applies the same validation rules to document inserts and updates to existing valid documents that match the validation rules. Updates to existing documents in the collection that don't match the validation rules aren't required to pass validation.MongoDB对与验证规则匹配的现有有效文档的文档插入和更新应用相同的验证规则。对集合中不符合验证规则的现有文档的更新不需要通过验证。

Prerequisite先决条件

The examples on this page use a contacts collection with these documents:此页面上的示例使用包含以下文档的contacts集合:

db.contacts.insertMany([
{ "_id": 1, "name": "Anne", "phone": "+1 555 123 456", "city": "London", "status": "Complete" },
{ "_id": 2, "name": "Ivan", "city": "Vancouver" }
])

Steps: Use strict Validation步骤:使用strict验证

The following example adds a strict validation to the contacts collection and shows the results when attempting to update invalid documents.以下示例为contacts集合添加了strict验证,并显示了尝试更新无效文档时的结果。

1

Specify validation rules with strict validation level.指定具有strict验证级别的验证规则。

Add a validator to the contacts collection with strict validationLevel:使用strict validationLevel将验证器添加到contacts集合中:

db.runCommand( {
collMod: "contacts",
validator: { $jsonSchema: {
bsonType: "object",
required: [ "phone", "name" ],
properties: {
phone: {
bsonType: "string",
description: "phone must be a string and is required"
},
name: {
bsonType: "string",
description: "name must be a string and is required"
}
}
} },
validationLevel: "strict"
} )

Because the validationLevel is strict, when any document is updated, MongoDB checks that document for validation.因为validationLevelstrict,当任何文档被更新时,MongoDB都会检查该文档的验证。

2

Test the validation.测试验证。

The following update commands modify both documents in the contacts collection such that neither of the documents are consistent with the validation rule which requires name to be a string:以下更新命令修改了contacts集合中的两个文档,使得这两个文档都不符合要求name为字符串的验证规则:

db.contacts.updateOne(
{ _id: 1 },
{ $set: { name: 10 } }
)

db.contacts.updateOne(
{ _id: 2 },
{ $set: { name: 20 } }
)
3

Observe results.观察结果。

Both update operations fail. MongoDB returns the following output for each operation:两次更新操作均失败。MongoDB为每个操作返回以下输出:

 MongoServerError: Document failed validation
Additional information: {
failingDocumentId: <id>,
details: {
operatorName: '$jsonSchema',
schemaRulesNotSatisfied: [
{
operatorName: 'properties',
propertiesNotSatisfied: [
{
propertyName: 'name',
description: 'name must be a string and is required',
details: [
{
operatorName: 'bsonType',
specifiedAs: { bsonType: 'string' },
reason: 'type did not match',
consideredValue: <value>,
consideredType: 'int'
}
]
}
]
},
{
operatorName: 'required',
specifiedAs: { required: [ 'phone', 'name' ] },
missingProperties: [ 'phone' ]
}
]
}
}

Steps: Use moderate Validation步骤:使用moderate验证

The following example adds a moderate validation to the contacts collection and shows the results when attempting to update invalid documents.以下示例向contacts集合添加了moderate验证,并显示了尝试更新无效文档时的结果。

1

Specify validation rules with moderate validation level.指定具有moderate验证级别的验证规则。

Add a validator to the contacts collection with moderate validationLevel:使用moderate validationLevel将验证器添加到contacts集合中:

db.runCommand( {
collMod: "contacts",
validator: { $jsonSchema: {
bsonType: "object",
required: [ "phone", "name" ],
properties: {
phone: {
bsonType: "string",
description: "phone must be a string and is required"
},
name: {
bsonType: "string",
description: "name must be a string and is required"
}
}
} },
validationLevel: "moderate"
} )

Because the validationLevel is moderate:因为validationLevelmoderate

  • If you update the document with _id: 1, MongoDB applies the new validation rules because the existing document meets the validation requirements.如果你用_id:1更新文档,MongoDB会应用新的验证规则,因为现有文档符合验证要求。
  • If you update the document with _id: 2, MongoDB does not apply the new validation rules because the existing document does not meet the validation requirements.如果用_id: 2更新文档,MongoDB不会应用新的验证规则,因为现有文档不符合验证要求。
2

Test the validation.测试验证。

The following update commands modify both documents in the contacts collection such that neither of the documents are consistent with the validation rule which requires name to be a string:以下更新命令修改了contacts集合中的两个文档,使得这两个文档都不符合要求名称为字符串的验证规则:

db.contacts.updateOne(
{ _id: 1 },
{ $set: { name: 10 } }
)

db.contacts.updateOne(
{ _id: 2 },
{ $set: { name: 20 } }
)
3

Observe results.观察结果。

MongoDB returns the following output for each operation:MongoDB为每个操作返回以下输出:

// _id: 1

MongoServerError: Document failed validation
Additional information: {
failingDocumentId: 1,
details: {
operatorName: '$jsonSchema',
schemaRulesNotSatisfied: [
{
operatorName: 'properties',
propertiesNotSatisfied: [
{
propertyName: 'name',
description: 'name must be a string and is required',
details: [
{
operatorName: 'bsonType',
specifiedAs: { bsonType: 'string' },
reason: 'type did not match',
consideredValue: 10,
consideredType: 'int'
}
]
}
]
}
]
}
}

// _id: 2

{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 0,
upsertedCount: 0
}

The output shows:输出显示:

  • The update fails for the document with _id: 1. This document met the initial validation requirements, and MongoDB applies validation rules to this document._id: 1的文档更新失败。此文档符合初始验证要求,MongoDB将验证规则应用于此文档。
  • The update succeeds for the document with _id: 2. This document did not meet the initial validation requirements, and MongoDB does not apply validation rules to this document._id: 2的文档更新成功。此文档不符合初始验证要求,MongoDB也不对此文档应用验证规则。

Important

The error output is intended for human consumption. It may change in the future and should not be relied upon in scripts.错误输出旨在供人类使用。它将来可能会发生变化,不应在脚本中依赖。

Learn More了解更多