Database Manual / Data Modeling / Schema Validation / Specify JSON Validation

Specify Allowed Field Values指定允许的字段值

When you create a JSON Schema, you can specify what values are allowed in a particular field. Use this functionality to ensure that your field values belong to an expected set of values, such as a list of countries. Similarly, you can use this functionality to prevent human error, such as typos, when inserting data into a collection.创建JSON模式时,可以指定特定字段中允许的值。使用此功能可确保字段值属于预期的一组值,例如国家列表。同样,您可以使用此功能来防止在将数据插入集合时出现人为错误,例如拼写错误。

Context上下文

To specify a list of allowed values, use the enum keyword in your JSON schema. The enum keyword means "enumerate", and is used to list possible values of a field.要指定允许的值列表,请在JSON模式中使用enum键。enum键表示“枚举”,用于列出字段的可能值。

Steps步骤

Consider a clothing company that only ships products to France, the United Kingdom, and the United States. In the validator, you can list the allowed country values and reject documents that specify a different country.考虑一家只向法国、英国和美国运送产品的服装公司。在验证器中,您可以列出允许的国家值,并拒绝指定其他国家的文档。

1

Create a collection with validation containing enum.创建一个包含enum的验证集合。

Create a shipping collection and use the $jsonSchema operator to set schema validation rules:创建shipping(发货)集合,并使用$jsonSchema运算符设置架构验证规则:

db.createCollection("shipping", {
validator: {
$jsonSchema: {
bsonType: "object",
title: "Shipping Country Validation",
properties: {
country: {
enum: [ "France", "United Kingdom", "United States" ],
description: "Must be either France, United Kingdom, or United States"
}
}
}
}
} )

The enum field in the country object only allows documents where the country field is either France, United Kingdom, or United States.country对象中的enum字段仅允许country字段为FranceUnited KingdomUnited States的文档。

2

Confirm that the validation prevents invalid documents.确认验证可防止无效文档。

The following insert operation fails because country is country, which isn't in the list of allowed values.以下插入操作失败,因为countrycountry,而country不在允许的值列表中。

db.shipping.insertOne( {
item: "sweater",
size: "medium",
country: "Germany"
} )

The operation returns this error:操作返回此错误:

MongoServerError: Document failed validation
Additional information: {
failingDocumentId: ObjectId("630d1057931191850b40d0aa"),
details: {
operatorName: '$jsonSchema',
title: 'Shipping Country Validation',
schemaRulesNotSatisfied: [
{
operatorName: 'properties',
propertiesNotSatisfied: [
{
propertyName: 'country',
description: 'Must be either France, United Kingdom, or United States',
details: [
{
operatorName: 'enum',
specifiedAs: {
enum: [ 'France', 'United Kingdom', 'United States' ]
},
reason: 'value was not found in enum',
consideredValue: 'Germany'
}
]
}
]
}
]
}
}
3

Insert a valid document.插入有效文档。

The insert succeeds after you change the country field to one of the allowed values:country字段更改为允许的值之一后,插入成功:

db.shipping.insertOne( {
item: "sweater",
size: "medium",
country: "France"
} )
4

Query for the valid document.查询有效文档。

To confirm that the document was successfully inserted, query the shipping collection:要确认文档已成功插入,请查询shipping集合:

db.shipping.find()

MongoDB returns the document:MongoDB返回文档:

[
{
_id: ObjectId("630d10d5931191850b40d0ab"),
item: 'sweater',
size: 'medium',
country: 'France'
}
]