문서 메뉴
문서 홈
/
MongoDB 매뉴얼
/ /

기존 문서에 대한 유효성 검사 수준 지정

이 페이지의 내용

  • 컨텍스트
  • 전제 조건
  • 단계: strict 유효성 검사 사용
  • 단계: moderate 유효성 검사 사용
  • 자세히 알아보기

유효성 검사를 추가하기 전에 컬렉션에 이미 존재하는 문서의 경우 MongoDB가 이러한 문서에 유효성 검사 규칙을 적용하는 방법을 지정할 수 있습니다.

스키마의 validationLevel 는 MongoDB가 유효성 검사 규칙을 적용하는 문서를 결정합니다.

유효성 검사 수준
행동
strict
(기본값) MongoDB는 모든 문서 삽입 및 업데이트에 동일한 유효성 검사 규칙을 적용합니다.
moderate
MongoDB는 유효성 검사 규칙과 일치하는 기존 유효 문서에 대한 문서 삽입 및 업데이트에 동일한 유효성 검사 규칙을 적용합니다. 유효성 검사 규칙과 일치하지 않는 컬렉션의 기존 문서에 대한 업데이트는 유효성을 검사하지 않습니다.

이 페이지의 예제에서는 이러한 문서와 함께 contacts 컬렉션을 사용합니다.

db.contacts.insertMany([
{ "_id": 1, "name": "Anne", "phone": "+1 555 123 456", "city": "London", "status": "Complete" },
{ "_id": 2, "name": "Ivan", "city": "Vancouver" }
])

다음 예시에서는 contacts 컬렉션에 strict 유효성 검사를 추가하고 유효하지 않은 문서를 업데이트하려고 할 때의 결과를 보여 줍니다.

1

strict validationLevel을 사용하여 contacts 컬렉션에 유효성 검사기를 추가합니다.

db.runCommand( {
collMod: "contacts",
validator: { $jsonSchema: {
bsonType: "object",
required: [ "phone", "name" ],
properties: {
phone: {
bsonType: "string",
description: "phone must be a string and is required"
},
name: {
bsonType: "string",
description: "name must be a string and is required"
}
}
} },
validationLevel: "strict"
} )

validationLevelstrict 이므로 문서가 업데이트되면 MongoDB는 해당 문서의 유효성을 검사합니다.

2

다음 업데이트 명령은 contacts 컬렉션의 두 문서를 모두 수정하여 어느 문서도 name 문자열이어야 하는 검증 규칙과 일치하지 않도록 합니다.

db.contacts.updateOne(
{ _id: 1 },
{ $set: { name: 10 } }
)
db.contacts.updateOne(
{ _id: 2 },
{ $set: { name: 20 } }
)
3

두 업데이트 작업 모두 실패합니다. MongoDB는 각 작업에 대해 다음과 같은 출력을 반환합니다.

MongoServerError: Document failed validation
Additional information: {
failingDocumentId: <id>,
details: {
operatorName: '$jsonSchema',
schemaRulesNotSatisfied: [
{
operatorName: 'properties',
propertiesNotSatisfied: [
{
propertyName: 'name',
description: 'name must be a string and is required',
details: [
{
operatorName: 'bsonType',
specifiedAs: { bsonType: 'string' },
reason: 'type did not match',
consideredValue: <value>,
consideredType: 'int'
}
]
}
]
},
{
operatorName: 'required',
specifiedAs: { required: [ 'phone', 'name' ] },
missingProperties: [ 'phone' ]
}
]
}
}

다음 예시에서는 contacts 컬렉션에 moderate 유효성 검사를 추가하고 유효하지 않은 문서를 업데이트하려고 할 때의 결과를 보여 줍니다.

1

moderate validationLevel을 사용하여 contacts 컬렉션에 유효성 검사기를 추가합니다.

db.runCommand( {
collMod: "contacts",
validator: { $jsonSchema: {
bsonType: "object",
required: [ "phone", "name" ],
properties: {
phone: {
bsonType: "string",
description: "phone must be a string and is required"
},
name: {
bsonType: "string",
description: "name must be a string and is required"
}
}
} },
validationLevel: "moderate"
} )

validationLevelmoderate 이기 때문입니다.

  • _id: 1로 문서를 업데이트하면 기존 문서가 유효성 검사 요구 사항을 충족하므로 MongoDB가 새 유효성 검사 규칙을 적용합니다.

  • _id: 2로 문서를 업데이트하면 기존 문서가 검증 요구 사항을 충족하지 않기 때문에 MongoDB는 새 유효성 검사 규칙을 적용하지 않습니다.

2

다음 업데이트 명령은 contacts 컬렉션의 두 문서를 모두 수정하여 어느 문서도 name 문자열이어야 하는 검증 규칙과 일치하지 않도록 합니다.

db.contacts.updateOne(
{ _id: 1 },
{ $set: { name: 10 } }
)
db.contacts.updateOne(
{ _id: 2 },
{ $set: { name: 20 } }
)
3

MongoDB는 각 작업에 대해 다음과 같은 출력을 반환합니다.

// _id: 1
MongoServerError: Document failed validation
Additional information: {
failingDocumentId: 1,
details: {
operatorName: '$jsonSchema',
schemaRulesNotSatisfied: [
{
operatorName: 'properties',
propertiesNotSatisfied: [
{
propertyName: 'name',
description: 'name must be a string and is required',
details: [
{
operatorName: 'bsonType',
specifiedAs: { bsonType: 'string' },
reason: 'type did not match',
consideredValue: 10,
consideredType: 'int'
}
]
}
]
}
]
}
}
// _id: 2
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 0,
upsertedCount: 0
}

출력에는 다음이 표시됩니다.

  • _id: 1 가 있는 문서에 대한 업데이트가 실패했습니다. 이 문서는 초기 유효성 검사 요구 사항을 충족했으며 MongoDB는 이 문서에 유효성 검사 규칙을 적용합니다.

  • _id: 2 이 있는 문서에 대한 업데이트가 성공했습니다. 이 문서는 초기 유효성 검사 요구 사항을 충족하지 않았으며, MongoDB는 이 문서에 유효성 검사 규칙을 적용하지 않습니다.

중요

오류 출력은 사람이 볼 수 있도록 만들어졌습니다. 향후 변경될 수 있으며 스크립트에 의존해서는 안 됩니다.

  • 유효하지 않은 문서 처리 방법 선택

  • 스키마 유효성 검사 수정

← 스키마 유효성 검사 수정