mongoose를 이용한 validate 설정
1. 에러 로그가 나올 수 있게 하는 예제
const schema = new mongoose.Schema({
name: { type: String, required: true }, // name 값이 있어야 한다.
password: String
});
const Users = mongoose.model('Users', schema);
async function createUsers() {
const users = new Users({
password: '12345678' // name이 빠졌다.
});
try {
const result = await course.save();
console.log(result);
} catch (ex) { // 오류가 발생해서 catch로 빠진다.
console.log(ex.message);
}
}
createUsers();
2. Built-in Validate 설정
const schema = new mongoose.Schema({
name: {
type: String,
minlength: 5, // 문자열 길이 조건
maxlength: 10,
match: /정규식/
},
job: {
type: String,
enum: ['teacher', 'student'] // teacher나 student 중 하나여야 한다.
},
age: {
type: Number,
min: 10, // 숫자 길이 조건
max: 50
}
});
3. Custom Validate 설정
(생략)