23.2.2 스태틱 메서드 만들기

    이번에는 스태틱 메서드를 만들어 보겠습니다. findByUsername이라는 메서드를 작성할 텐데요. 이 메서드는 username으로 데이터를 찾을 수 있게 해 줍니다.

    src/models/user.js

    import mongoose, { Schema } from 'mongoose';
    import bcrypt from 'bcrypt';
    
    const UserSchema = new Schema({
      username: String,
      hashedPassword: String,
    });
    
    UserSchema.methods.setPassword = async function(password) {
      const hash = await bcrypt.hash(password, 10);
      this.hashedPassword = hash;
    };
    
    UserSchema.methods.checkPassword = async function(password) {
      const result = await bcrypt.compare(password, this.hashedPassword);
      return result; // true / false
    };
    
    UserSchema.statics.findByUsername = function(username) {
      return this.findOne({ username });
    };
    
    const User = mongoose.model('User', UserSchema);
    export default User;

     

    스태틱 함수에서의 this는 모델을 가리킵니다. 지금 여기서는 User를 가리키겠지요?

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.