최근 MongoDB (버전 3.2.9)에 대한 작업을 시작했으며 데이터베이스 수준의 일관성이 좋기 때문에 검증 기능을 사용하려고했습니다.MongoDB의 검사기가 작동하지 않습니다.
이미 알고있는 것처럼 비즈니스 논리에서이 유효성 검사를 수행 할 수 있고해야만한다는 것을 알고 있습니다. 하지만 추가 보안 계층이있는 것이 좋습니다.
은 I 형은'string'
유형의
'int'
_id
,
name
입력
'string'
의
desc
으로 수집
category
을 추가하는 시도.
이 값들은 모두 존재해야하지만 내용에 대한 제한은 제시되지 않습니다.
는 이제 manual 다음, 나는 다음과 같은 코드로 끝났다 : 이미 간단한 구조로, 그러나
db.createCollection('category', {
validator: { $or:
[
{ _id: { $and: [ { $exists: true },
{ $type: 'int' } ] } },
{ name: { $and: [ { $exists: true },
{ $type: 'string' } ] } },
{ desc: { $and: [ { $exists: true },
{ $type: 'string' } ] } }
]
}
})
, MongoDB를 불평 : 이제
{ "ok" : 0, "errmsg" : "unknown operator: $and", "code" : 2 }
, this similar question을 찾았으나 여러 개의 제약 조건을 직접 입력하려고했습니다.그것은, 내가 지금 다음 insert
명령 중 하나를 실행할 수 있어야 같은 컬렉션을 만들 않지만
db.createCollection('category', {
validator: { $or:
[
{ _id: { $exists: true } },
{ _id: { $type: 'int' } },
{ name: { $exists: true } },
{ name: { $type: 'string' } },
{ desc: { $exists: true } },
{ desc: { $type: 'string' } }
]
}
})
하지만 지금은 : 10 개 배열
db.category.insert({})
db.category.insert({_id: 17, name: '', desc: 'valid'})
db.category.insert({_id: 42, name: 42, desc: ''})
db.category.insert({_id: 43, name: '', desc: 42})
db.category.insert({_id: '', name: 42, desc: 42})
db.category.find()
지금
{ "_id" : ObjectId("57e19650b10ab85eca323684") }
{ "_id" : 17, "name" : "", "desc" : "valid" }
{ "_id" : 42, "name" : 42, "desc" : "" }
{ "_id" : 43, "name" : "", "desc" : 42 }
{ "_id" : "", "name" : 42, "desc" : 42 }
반환
최후의 수단으로 $or
연산자를 $and
으로 변경하려고 시도했습니다. 모든 규칙이 유효해야합니다. 적어도 하나. 나에게 가장 합리적인 것 같습니다이 방법
db.createCollection('category', {
validator: { $and:
[
{ _id: { $exists: true } },
{ _id: { $type: 'int' } },
{ name: { $exists: true } },
{ name: { $type: 'string' } },
{ desc: { $exists: true } },
{ desc: { $type: 'string' } }
]
}
})
, 그것은 그러나 모든에
을 작동하지 않습니다. , db.version()
반환 3.2.9
에, 위의 전화를 언급 한 바와 같이 WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 121,
"errmsg" : "Document failed validation"
}
})
: inserts
언급 위의 상관없이 나는 모든 날 같은 오류를주는 것도 작동하지, 마음은 5 점 만점 하나의 유효한 거기 당신, 사용하여 시도 이전에 비어있는 디렉토리로 설정된 --dbpath
매개 변수 만있는 Windows 컴퓨터에서 기본 MongoDB 64 비트 배포를 실행하고 있습니다.