상세 컨텐츠

본문 제목

ch6.19~ edit video & Middlewares

노마드/유튜브

by hippo0207 2022. 8. 19. 13:51

본문

1. Video detail

  • id가 숫자만으로 안되서 (\\d+)랑 안맞음 >> 수정필요
  • /upload를 /:id위로 올려주고
  • 아니면 regex새로만들기
  • objectId : 24byte 16진수임

\

videoRouter.get("/:id([0-9a-f]{24})", watch);
videoRouter.route("/:id([0-9a-f]{24})/edit").get(getEdit).post(postEdit);
videoRouter.route("/upload").get(getUpload).post(postUpload);
  • id 로 video찾아오기 : Model.findById()  or Model.findOne()로 가능
    • findOne() >> 보낸 모든 condition 적용시킴
export const watch = async (req, res) => {
  const { id } = req.params;
  const video = await Video.findById(id);     <<     <<
  return res.render("watch", { pageTitle: video.title, video });     <<     <<
};

2. Edit Video

  • exec() :: 실행하는거
  • >> 이거붙이면 > 내부적으로 promise가 return됨  ( await Video.findById(id).exec());)
  • >> 신경안써도됨. exec()제거 ( async, await 쓰고있으니까 )
 
  • 없는 비디오 호출할경우?  >> video = null >> null.title하려니 안됨   에러처리
export const watch = async (req, res) => {
  const { id } = req.params;
  const video = await Video.findById(id);
  if (!video) {
    return res.render("404", { pageTitle: "Video not found" });
  }
  return res.render("watch", { pageTitle: video.title, video });
};

========
[404.pub]
extends base

>> return을 꼭 넣어줘야함 . 안하면 밑에꺼 도 다 실행해버림

  • Edit 페이지 수정하기
export const getEdit = async (req, res) => {
  const { id } = req.params;
  const video = await Video.findById(id);
  if (!video) {
    return res.render("404", { pageTitle: "Video not found" });
  }
  return res.render("edit", { pageTitle: `Edit ${video.title}`, video });
};
  • edit.pug >> hashtags 가 ["#ㅁㄴㅇㄹㅁㄴㅇㄹ"] 이런식으로 나온다. array로 
    • hashtags formatting필요함 >> video.hashtags.join() 으로 string화
    • # 있는건 그대로, #없는건 #붙이기 설정하기 >> startsWith사용
video.hashtags = hashtags
    .split(",")
    .map((word) => (word.startsWith("#") ? word : `#${word}`));
  • req.body 하나하나 바꾸는거? >> 이건좀 구리다
  video.title = title;
  video.description = description;
  video.hashtags = hashtags
await Video.findByIdAndUpdate(id, {
    title,
    description,
    hashtags: hashtags
      .split(",")
      .map((word) => (word.startsWith("#") ? word : `#${word}`)),
  });
  • 그리고 postEdit 에선 기존의 findById 로 비디오찾는거보다 exist({ filter조건}) 가 더낫다
    • exist({ _id: id}) >> true, false만 리턴
    • findById  >> video객체로 리턴 >> 이건 여기선 필요없어서
//const video = await Video.findById(id);
const video = await Video.exists({_id:id});
  • hashtags 처리 깔꼼하게
    • 기존 : 저장전에 해시태그 처리
    • 저장전에 처리하는과정을 거칠수 있음
    • >> middlewares 를 사용하면 더 깔끔 해 짐 or pre, post, hook 도 있음
    • 끼어들 틈을 만들어주는 것들

3. Middlewares

= hooks  >> 이용해서 hashtags 깔끔하게 정리하기

  • model만들기 전 위치에 생성해야함
videoSchema.pre("save", async function () {
  console.log("Wa are about to save:", this);
});

const Video = mongoose.model("Video", videoSchema);
export default Video;
  • >> this.이용해서 이것저것 가눙
videoSchema.pre("save", async function () {
  this.hashtags = this.hashtags[0]
    .split(",")
    .map((word) => (word.starstWith("#") ? word : `#${word}`));
});
  • postEdit 용 middleware하나 더필요함
    • findByIdAndUpdate() >> hook 실행 안함 & 실행중인 데이터에 접근이 불가능함
    • >> 위처럼 pre("save" ~~) 방식으로는 안됨. save, update 두개가 다 필요해서. 이거보다 다른거 >>
    • 방법1 : videos.js 에 위함수 따로만들기
[videos.js]

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

=============
import Video, { formatHashtags } from "../models/Video";

~~
hashtags: formatHashtags(hashtags),
    });~~
  • 방법2 : static 사용하기 << 함수만들기 Video.함수명
videoSchema.static("formatHashtags", function (hashtags) {
  return hashtags.split(",").map((word) => (word.startsWith("#") ? word : `#${word}`));
});

==============
hashtags: Video.formatHashtags(hashtags),

>> import, export필요가 없음,,쿨,,

 

  • hashtags 보이게 mixin 추가하기
        ul
            each hashtag in video.hashtags
                li=hashtag

 

'노마드 > 유튜브' 카테고리의 다른 글

ch7. User authentication  (0) 2022.08.23
ch6.25~ delete, search  (0) 2022.08.22
ch6.14~ creating video, exception & validation  (0) 2022.08.18
ch6.8~ mongo  (0) 2022.08.17
ch6. mongoDB & Mongoose  (0) 2022.08.16

관련글 더보기

댓글 영역