이번엔 User
에 대한 스키마를 생성해보겠다.
우선 mongodb에 대한 스키마를 생성하기 때문에 mongoose
라이브러리를 사용한다는 코드를 입력해준다.
const mongoose = require('mongoose');
내가 입력한 User
에 대한 값들은 아래와 같다.
const userSchema = mongoose.Schema({
name: {
type: String,
maxlength: 50
},
email: {
type: String,
trim: true, //space(띄어쓰기) 관리
unique: 1 //같은 값이 들어갈 수 없도록 설정
},
password: {
type: String,
minlength: 8
},
role: {
type: Number,
default: 0
},
image: String,
token: {
type: String
},
tokenExp: { //토큰 유효기간
type: Number
}
})
아마 보면 바로 이해가 되겠지만, 하나씩 설명을 써보겠다.
- name -
type
:String
(문자열),maxlength
(최대 길이)- email -
type
:String
(문자열),trim
(space 관리),unique
(중복값X)
trim 예 )ming@gmail.com
==min g@gmail.com
-> 띄어쓰기 되어있어도 없는 것으로 취급- password -
type
:String
(문자열),minlength
(최소 길이)- role -
type
:Number
(숫자),default
(기본값)
role 의미 예 ) 관리자, 일반 유저 등- image -
String
(문자열)- token -
type
:String
(문자열)- tokenExp -
type
:Number
(숫자)
이렇게 정의된 User
스키마를 다른 곳에서도 이용해야하기 때문에 이를 내보낸다는 코드를 입력해야한다.
const User = mongoose.model('User', userSchema)
module.exports = { User }
이렇게 입력한 userSchema
를 User
라는 이름으로 선언하고 이를 내보내는 module.exports
를 입력한다. 이렇게 입력하면, 다른 파일에서도 이 User
에 대해 접근이 가능하다.
const mongoose = require('mongoose');
const userSchema = mongoose.Schema({
name: {
type: String,
maxlength: 50
},
email: {
type: String,
trim: true, //space(띄어쓰기) 관리
unique: 1 //같은 값이 들어갈 수 없도록 설정
},
password: {
type: String,
minlength: 8
},
role: {
type: Number,
default: 0
},
image: String,
token: {
type: String
},
tokenExp: { //토큰 유효기간
type: Number
}
})
const User = mongoose.model('User', userSchema)
module.exports = { User }
참고로 이 User.js
파일은 models
폴더를 생성하여 해당 폴더 안에 생성하였다.