프로그래밍/프론트엔드

[nodejs] 비밀번호 해시 bcrypt.hash, 테이블 참조 populate

제로스크랩 2023. 3. 29. 08:37

노마드코더 유튜브 클론코딩 #8.14 Bugfix 공부내용 정리

  • 비디오 업로드시 유저비밀번호를 해시하던 현상 수정
    • 유저가 비밀번호 변경시에만 해시되도록 수정 == isModified("password")
userSchema.pre("save", async function () {
    if (this.isModified("password")) {
        this.password = await bcrypt.hash(this.password, 5);
    }
})

 

  • 비디오 수정,삭제시 비디오 소유권자만 작업할 수 있도록 기능추가
    • story.owner의 타입은 object이고 _id의 타입은 String이므로 ' !== ' 연산자로 비교가 불가능하기 때문에 String으로 형변환을 해줘야한다.
const { user: { _id } } = req.session;

if (String(story.owner) !== String(_id)) {
    return res.status(403).redirect("/");
}

 

  • 비디오 삭제시에는 비디오 소유권자의 아이디 값만 필요하기 때문에 populate를 쓸 필요가 없다.
    • populate는 선택된 칼럼에 참조된 테이블의 정보가 필요할 때만 사용해서 불필요한 db호출을 줄이는 것이 좋다.
const story = await Story.findById({ _id: id });

if (!story) {
    return res.status(404).render("404", { pageTitle: "Story not found." });
}

if (String(story.owner) !== String(_id)) {
    return res.status(403).redirect("/");
}

 

git참조: https://github.com/overscrap/wetube-second/commit/76b0843da1aab6dbb8cc388f3b5f83f98758e0b4

728x90
반응형

'프로그래밍 > 프론트엔드' 카테고리의 다른 글

[React] react-hook-form 활용  (0) 2023.06.06
[ReactJs, NextJs] 자주쓰는 패키지 설치 명령어 정리  (0) 2023.06.06
[CSS] scss의 장점  (0) 2023.01.25
[CSS] Grid Garden  (0) 2023.01.22
[CSS] Grid property 정리  (0) 2023.01.21