User model, User Route

김종민·2022년 10월 25일
0

Youtube

목록 보기
8/23

  1. models에 User.js인 userSchema만들기
  2. userController만들기.

1. src/models/User.js

import mongoose from 'mongoose' ///mongoose는 무조건 import
import bcrypt from 'bcrypt' ///password hash화를 위해서~

// export const formatHashtags = (hashtags) =>
//   hashtags.split(',').map((word) => (word.startsWith('#') ? word : `#${word}`))

const userSchema = new mongoose.Schema({
  email: { type: String, required: true, unique: true },
  username: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  name: { type: String, required: true },
  location: String,
})
///userSchema에 들어갈 field, email과 username만 unique로 설정.

userSchema.pre('save', async function () {
  console.log('111', this.password)
  this.password = await bcrypt.hash(this.password, 5)
  console.log('222', this.password)
})
///.pre를 이용해서 DB에 save되기전에 req.body로 넘어온 password가
///bcrypt.hash, 즉 hash화 되어서 DB에 저장되게 함.
///console은 DB에 입력 전 후가 어떻게 다른지 확인.
///this.password뒤에 숫자 5는 다섯번 돌린다는 뜻임. 그냥 5~10사이면 됨.

const User = mongoose.model('User', userSchema)
///User model을 만들어서 export함.
export default User

2. src/routes/rootRouter.js

확인만 할 것!

import express from 'express'
import {
  getJoin,
  getLogin,
  postJoin,
  postLogin,
} from '../controllers/userController'
import { search, trending } from '../controllers/videoController'

const rootRouter = express.Router()

rootRouter.get('/', trending)
rootRouter.route('/join').get(getJoin).post(postJoin)
rootRouter.route('/login').get(getLogin).post(postLogin)
rootRouter.get('/search', search)

export default rootRouter

3. src/routes/userRouter.js

확인만~

import express from 'express'
import { editUser, logoutUser, removeUser, seeUser } from '../controllers/userController'

const userRouter = express.Router()

userRouter.get('/:id(\\d+)', seeUser)
userRouter.get('/edit', editUser)
userRouter.get('/remove', removeUser)
userRouter.get('/logout', logoutUser)

export default userRouter
profile
코딩하는초딩쌤

0개의 댓글