허용된 필드 값 지정
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.
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.
단계
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
.
0} 컬렉션을 $jsonSchema
만들고
shipping
연산자를 사용하여 스키마 유효성 검사 규칙을 설정합니다.
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' } ] } ] } ] } }