• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

new true에 관 해

20.11.23 16:00 작성 조회수 125

0

new를 설정해야 반드시 업데이트가 적용된다고 하셨는데, routes/api/post.js 파일에 195번째줄과 같이 findByIdAndUpdate를 사용한 구문이 여러개 있는데, 여기선 new true를 적용을안해도 동작하나요?

답변 1

답변을 작성해보세요.

0

네 그렇습니다. Update라는 의미를 잘 생각해보시기 바랍니다. 

0228님을 비롯하여 많은 분들이 이 부분이 sequelize랑 다른 것 같아서 많이들 물어보십니다. 

우리가 jwt token을 쓰면서 비번을 해쉬값을 바꿔주는 방법에는 크게 2가지가 있습니다. 

1번째는 지금 보여드린 비교적 직접적인 방법과

2번째는 mongoose이든 sequelize이든 hook라는 것이 존재하는데, DB에 저장하기 직전에 일정한 규칙을 만들어 비번값을 바꿔주는 코드를 짜서 저장하는 좀더 고급스러운 방법이 있습니다. 

import mongoose from "mongoose";
import bcrypt from "bcryptjs";

const userSchema= mongoose.Schema(
{
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
isAdmin: {
type: Boolean,
required: true,
default: false,
},
},
{
timestamps: true,
}
);

user.methods.matchPassword = async function (enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password);
};

userSchema.pre("save", async function (next) {
if (!this.isModified("password")) {
next();
}

const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
});

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

export default User;
이건 제가 다른 곳에서 쓰는 코드인데 참고하시기 바랍니다. (이부분은 리뉴얼강의시 업데이트 될 것입니다)
(NodeJS 최신버전으로 만들예정)