Specify Allowed Field Values指定允许的字段值
On this page本页内容
When you create a JSON Schema, you can specify what values are allowed in a particular field. 创建JSON模式时,可以指定特定字段中允许的值。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.同样,在将数据插入集合时,您可以使用此功能来防止人为错误,例如打字错误。
Context上下文
To specify a list of allowed values, use the 要指定允许值的列表,请在JSON架构中使用enum
keyword in your JSON schema. enum
键。The enum
keyword means "enumerate", and is used to list possible values of a field.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.在验证器中,您可以列出允许的国家/地区值,并拒绝指定不同国家/地区的文档。
Create a collection with validation containing enum
.创建一个包含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
字段为France
、United Kingdom
或United States
的文档。
Confirm that the validation prevents invalid documents.确认验证可以防止无效文档。
The following insert operation fails because 以下插入操作失败,因为country
is Germany
, which isn't in the list of allowed values.country
是Germany
,而Germany
不在允许的值列表中。
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'
}
]
}
]
}
]
}
}
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'
}
]