[Node.js/React] MongoDB 스키마 생성

·2023년 6월 11일
0

node-react 기초 공부

목록 보기
3/12
post-thumbnail

이번엔 User에 대한 스키마를 생성해보겠다.

✏️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
    }
})

아마 보면 바로 이해가 되겠지만, 하나씩 설명을 써보겠다.

  1. name - type: String (문자열), maxlength (최대 길이)
  2. email - type: String (문자열), trim (space 관리), unique (중복값X)
    trim 예 ) ming@gmail.com == min g@gmail.com
    -> 띄어쓰기 되어있어도 없는 것으로 취급
  3. password - type: String (문자열), minlength (최소 길이)
  4. role - type: Number (숫자), default (기본값)
    role 의미 예 ) 관리자, 일반 유저 등
  5. image - String (문자열)
  6. token -type: String (문자열)
  7. tokenExp - type: Number (숫자)

이렇게 정의된 User 스키마를 다른 곳에서도 이용해야하기 때문에 이를 내보낸다는 코드를 입력해야한다.

const User = mongoose.model('User', userSchema)

module.exports = { User }

이렇게 입력한 userSchemaUser라는 이름으로 선언하고 이를 내보내는 module.exports를 입력한다. 이렇게 입력하면, 다른 파일에서도 이 User에 대해 접근이 가능하다.

User.js 코드

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폴더를 생성하여 해당 폴더 안에 생성하였다.


👩‍💻 깃허브 주소

node-react

0개의 댓글