티스토리 뷰

#Node.js

 

 

오늘은 유저 패스워드 변경을 하기 위한 로직을 구현했다.

 

// post 함수 구현 

export const postChangePassword = async (req, res) => {
  const {
    body: { oldPassword, newPassword, newPassword1 },
    user
  } = req;
  try {
    if (newPassword !== newPassword1) {
      res.status(400);
      return res.redirect(`/users/${routes.changePassword}`);
    }
    await user.changePassword(oldPassword, newPassword);
    return res.redirect(routes.me);
  } catch (error) {
    res.status(400);
    return res.redirect(`/users/${routes.changePassword}`);
  }
};

// post가 작동할 Router
userRouter.post(routes.changePassword, onlyPrivate, postChangePassword);



 

오류가 발생한 경우, res.status(400) 을 해주지 않으면 구글에서 성공한 것으로 인식하여 패스워드를 변경할 것이냐 물어보기 때문에 400을 내려줬다. 

 

 

추가로, Video 업로더를 한 유저가 누군지 알 수 있게 로직을 추가했다.

 

// user.js

import mongoose from 'mongoose';
import passportLocalMongoose from 'passport-local-mongoose';

const UserSchema = new mongoose.Schema({
  name: String,
  email: String,
  avatarUrl: String,
  facebookId: Number,
  githubId: Number,
  comments: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Comment"
    }
  ],
  videos: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Video"
    }
  ]
});

// passport-local-mongoose는 passport를 사용한 이름 및 비밀번호 로그인을 단순화 시키는 mongoose 플러그인
// usernameField를 UserSchame의 email로 설정하겠다는 뜻.
UserSchema.plugin(passportLocalMongoose, { usernameField: 'email' });

const model = mongoose.model('User', UserSchema);

export default model;


// Video.js

import mongoose from "mongoose";

// schema는 형태 (definition)를 의미함. 형태를 만드는 것

const VideoSchema = new mongoose.Schema({
  // required : 값에 문제가 있어 (값이 오지 않아) 에러가 발생할 경우 뱉게 됨.
  // type은 mongoose 에서 어떤 타입을 사용할 수 있는지 확인 가능.
  fileUrl: {
    type: String,
    required: "File URL is required"
  },
  title: {
    type: String,
    required: "Tilte is required"
  },
  description: String,
  views: {
    type: Number,
    default: 0
  },
  createdAt: {
    type: Date,
    default: Date.now
  },
  comments: [
    // type은 객체의 ID를 얻게 됨, ref는 어디를 참고할 것인지, Comment의 이름을 가진 model이 참고됨.
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Comment"
    }
  ],
  creator: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User"
  }
});

// model의 이름은 "Video", Schema는 위의 변수. mongoose.model('이름', '스키마')
const model = mongoose.model("Video", VideoSchema);
export default model;

 

User Model에 videos 배열을 생성 후 Video를 참고하게 했고, Video. Model에는 User를 참고하게 했다. 

 

  const newVideo = await Video.create({
    fileUrl: path,
    title,
    description,
    creator: user.id
  });

user.videos.push(newVideo.id);

const video = await Video.findById(id).populate("creator");
res.render('videoDetail', { pageTitle: video.title, video });

 

비디오 업로드 시 비디오 아이디를 푸쉬하고, 해당 동영상 상세 페이지로 가면 비디오의 id를 DB에서 찾고, 

populate로 해당 id의 객체를 가져와 상세 페이지에 랜더해주는 구조로 구현됐다. 

'TIL' 카테고리의 다른 글

2020-07-01 Customize Video Player  (0) 2020.07.01
2020-06-30 Node.js 라우터 가드  (0) 2020.06.30
2020-06-25 TIL  (0) 2020.06.25
2020-06-24 TIL  (0) 2020.06.24
2020-06-23 TIL  (0) 2020.06.23
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함