코딩딩/Error

mongoose save 무한 freezed

전낙타 2024. 10. 10. 11:00

진짜 바보같은 실수지만 그래도 기록은 해야지...

 

passport를 이용해 구글 login을 구현하던 중 save 단계에서 무한 츠쿠요미가 발생하는 문제가 발생했다.

const googleStrategyConfig = new GoogleStrategy({
    clientID: googleClientID,
    clientSecret: googleClientSecret,
    callbackURL: googleCallbackURL,
    scope: ['email', 'profile']
}, (accessToken, refreshToken, profile, done) => {
    console.log("profile = ", profile)
    User.findOne({googleId: profile.id})
        .then(existingUser => {
            if (existingUser) {
                console.log("existingUser = ", existingUser)
                done(null, existingUser);
            } else {
                console.log("profile.emails[0].value = ", profile.emails[0].value)
                const user = new User({googleId: profile.id, email: profile.emails[0].value})
                console.log("user = ", user)
                // 문제발생!!!!!!!!!!!!!
                user.save()
                    .then(user => done(null, user))
                    .catch(err => done(err));
            }
        })
        .catch(err => done(err));
});
passport.use('google', googleStrategyConfig);



처음엔 mongoose 버전 문제인가 싶어 버전도 낮추고 별에 별 짓을 다해봤는데 내 예상과 달리 그냥 코드를 바보같이 짠거였다.

userSchema.pre('save', function (next) {
    let user = this;
    console.log("pre user = ", user)
    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();
            });
        })
    } // ???????
});

 

Google login같은 경우 다음과 같은 형식으로 user 객체를 생성한다.

user =  {
  email: 'test@gmail.com',
  googleId: '123...',
  _id: new ObjectId('123...')
}

 

Oauth 2.0 로그인 방식으로는 해당 도메인에 인증 절차를 인가함으로 password가 따로 필요하지 않아 해당 middleware단에서 next가 호출되지 않았던 것....

 

userSchema.pre('save', function (next) {
    let user = this;
    console.log("pre user = ", user)
    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();
            });
        })
    } else {
        next(); // 문제해결........
    }
});

 

아직 middleware단 작성에 익숙하지 않아 벌어진 실수같다..

 

그래도 해결했으니 럭키비키여