指定允许的字段值
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.
上下文
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.
步骤
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
.
创建 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
.
确认验证可以防止无效文档。
The following insert operation fails because country
is
Germany
, which isn't in the list of allowed values.
db.shipping.insertOne( { item: "sweater", size: "medium", country: "Germany" } )
操作返回此错误:
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' } ] } ] } ] } }