본문 바로가기

JavaScript

mongoose에서 화살표 함수(arrow function)이 동작하지 않는 이유

javascript에서 제공하는 this는 예외적으로 화살표 함수를 사용할 수 없다.

 

문제 발생


회원가입 API 호출 시 결과가 false인 경우 오류 메시지가 나오도록 구현하였는데 따로 오류 메시지가 출력되지 않음.

오류 메시지가 출력되지 않은 이유는 아직 파악하지 못함.

원인


결론, this는 화살표 함수를 사용하지 못한다.

  • moogoose 패키지의 userSchema.pre() 함수 사용하여 비밀번호 암호화하는 기능을 구현
  • 비밀번호 정보르르 불러오기 위하여 스키마 정보를 this로 조회
userSchema.pre("save", (next) => {
  let user = this;
  if (user.isModified("password")) {
    // 비밀번호를 암호화
    bcrypt.genSalt(saltRounds, (err, salt) => {
      if (err) return next(err);

      bcrypt.hash(user.password, salt, (err, hash) => {
        if (err) return next(err);

        user.password = hash;
        next();
      });
    });
  }
});

해결


화살표 함수(arrow function)를 function() 형태로 변경

userSchema.pre("save", function(next) {
  let user = this;
  if (user.isModified("password")) {
    // 비밀번호를 암호화
    bcrypt.genSalt(saltRounds, function(err, salt) {
      if (err) return next(err);

      bcrypt.hash(user.password, salt, function(err, hash) {
        if (err) return next(err);

        user.password = hash;
        next();
      });
    });
  }
});

 

 

출처: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

 

Arrow function expressions - JavaScript | MDN

An arrow function expression is a compact alternative to a traditional function expression, but is limited and can't be used in all situations.

developer.mozilla.org

 

반응형