본문 바로가기

Youtube Clone Coding

User(사용자) 만들기

새로운 스키마가 필요해졌다. 사용자는 영상과는 다른 정보 이므로 새로운 스키마를 만들어준다.

import mongoose from "mongoose";

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,
});

const User = mongoose.model("User", userSchema);
export default User;

여기서 unique는 말 그대로 하나만 있어야 한다는 것이다. 스키마에 해당 정보에 관련된 내용을 정리해 주었다. 그리고 해당 스키마로 모델을 만들어 준 후 export 해주어 다른 파일에서도 쓸 수 있게 했다.

 

회원 가입 하는 페이지를 join.pug로 만들어준 후, 컨트롤러와 라우터를 설정해주었다. 회원가입에는 get, post 둘다 사용되므로, route메서드를 사용했다. 

rootRouter.route("/join").get(getJoin).post(postJoin);

getJoin 과 postJoin 컨트롤러를 보자.

export const getJoin = (req, res) => res.render("join", { pageTitle: "회원가입" })
export const postJoin = async (req, res) => {
    const { name, username, email, password, location } = req.body;
    await User.create({
        name,
        username,
        email,
        password,
        location,
    });
    return res.redirect("/login");
};

getJoin은 join.pug를 렌더링 하여 회원가입 페이지 임을 알려주고 있다. postJoin에서는 request의 body에서 입력된 값들을 받아와서 User.create() 메서드로 디비에 저장하고 있다. 이때 create가 완료 될때까지 페이지가 login페이지로 redirect되지 않게끔 await를 사용했다. 그리고 완료되면 로그인 페이지로 이동하게끔 작성했다.

'Youtube Clone Coding' 카테고리의 다른 글

Form validation  (0) 2022.11.14
사용자 비밀번호 해싱  (0) 2022.11.11
Search 페이지  (0) 2022.11.11
영상 수정하기  (0) 2022.11.09
Video 만들기  (0) 2022.11.09