Docs Home → Develop Applications → MongoDB Manual
On this page本页内容
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. 创建JSON模式时,可以指定特定字段中允许的值。使用此功能可确保字段值属于预期的值集,例如国家列表。Similarly, you can use this functionality to prevent human error, such as typos, when inserting data into a collection.类似地,在将数据插入集合时,可以使用此功能防止人为错误,例如键入错误。
To specify a list of allowed values, use the 要指定允许值的列表,请在JSON模式中使用enum
keyword in your JSON schema. enum
关键字。The enum关键字表示“enumerate”,用于列出字段的可能值。enum
keyword means "enumerate", and is used to list possible values of a field.
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.在验证器中,您可以列出允许的国家/地区值,并拒绝指定不同国家/地区的文档。
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" } } } } } )
Theenum
field in thecountry
object only allows documents where thecountry
field is eitherFrance
,United Kingdom
, orUnited States
.country
对象中的enum
字段仅允许country
字段为France
、United Kingdom
或United States
的文档。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' } ] } ] } ] } }country: "France" } ) 4