• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

User.js 안에서 var user = this; 에 대한 궁금증

21.07.20 17:49 작성 조회수 139

0

userSchema.pre("save"function (next) {
  var user = this;
  
  //user == userSchema

  if (user.isModified("password")) {
    //model 속 field 안에 'password'가 바뀔때만.
    //비밀번호를 암호화 시킨다.
    bcrypt.genSalt(saltRoundsfunction (errsalt) {
      if (errreturn next(err);
      //next 하면 index.js user.save function으로 바로 넘어간다.
      bcrypt.hash(user.passwordsaltfunction (errhash) {
        //hash == 암호화된 비밀번호
        //user.password ==> plainPassword
        if (errreturn next(err);
        user.password = hash;
        next();
      });
    });
  }
});

userSchema.pre("save", function (next) {
   var user = this;

}

이 부분에 대한 궁금증입니다.

하단에 user.password =hash로 쓰기위해 

var user = this; 를 쓴다는것을 그냥 보면 알겠는데,

제 머릿속에서는 var user = this.userSchema라고 선언을 해야 

user에 userSchema가 담길것같은데 그냥 this;로 진행해도 실행이 되서 좀 의아해서 질문글을 올립니다. 

답변 1

답변을 작성해보세요.

0

TaeHyeon Kim님의 프로필

TaeHyeon Kim

2021.07.25

제가 알기론 스키마는 User의 구조를 의미하는 거라, 회원 정보를 담을 땐 User를 담아야 하는 걸로 알고있어요.

// request에서 회원 정보 가져오기
const user=new User(req.body);
    user.save((err, doc)=>{
        // 몽고디비에 저장
    });

위 index.js에서 user.save를 진행하면

User.js의 userSchema에 [request에서 받은 user 정보]를 담기 위한 코드여서 this(user)로 진행해야 정보가 담기는 듯합니다.

실제로 console.log로 테스트해보면 아래와 같은 결과가 뜹니다.

const user=this;
console.log(this); // 유저 정보 json형태
console.log(this.Schema); //undefined
console.log(user); // 유저 정보 json형태
console.log(user.Schema); //undefined

조금이나마 도움이 되면 좋겠어서 답변을 달았습니다 :)

부족하거나 잘못된 정보가 있다면 추가로 댓글 및 답변 부탁드립니다!