노드 리액트 기초 강의 #11 로그인 기능 with Bcrypt (1)

User.js

userSchema.pre('save', function (next) {

    var user = this

    //비밀번호를 암호화 한다. 
    if (user.isModified('password')) { // 기존 데이터의 비밀번호를 바꿀 때는 적용 안된다.  
        const saltRounds = 10;
        bcrypt.hash(user.password, saltRounds, function (err, hash) {
            if (err) return next(err)
            user.password = hash
            next() // 이곳에 붙으면 암호화가 된다
        }); 
        next() // 이곳에 붙으면 암호화가 안된 비밀번호가 디비에 저장 된다
    } else { return next() }
})

코드의 순서를 콘솔로그로 확인하니 bcrypt.hash 이 부분이 index.js의 save부분보다 나중에 실행되었다. pre함수지만 pre하지 않은 부분이었다. 따라서 이 부분을 고쳐야 했다.

나는 async/await로 고쳤다. 그러면 예상대로 코드가 진행된다.

userSchema.pre('save', async function (next) {

    const user = this 
    //비밀번호를 암호화 한다. 
    if (user.isModified('password')) {  
        const saltRounds = 10;
        const hash = await bcrypt.hash(user.password, saltRounds);  
        user.password = hash
        return next() 
    } else { return next() }
})

댓글을 작성해보세요.