Mongoose: ์‚ฌ์ „ ์ €์žฅ ํ›„ํฌ๋Š” ๋ฌธ์„œ๋ฅผ ์ œ๊ณตํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค

์— ๋งŒ๋“  2015๋…„ 09์›” 02์ผ  ยท  3์ฝ”๋ฉ˜ํŠธ  ยท  ์ถœ์ฒ˜: Automattic/mongoose

'this'๊ฐ€ ์ €์žฅ๋˜๋Š” ๋ฌธ์„œ๋ฅผ ์ œ๊ณตํ•ด์•ผ ํ•˜์ง€๋งŒ ๋Œ€์‹  undefined๋ฅผ ์ œ๊ณตํ•˜๋Š” ์‚ฌ์ „ ์ €์žฅ ํ›„ํฌ์— ๋ฌธ์ œ๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค.

import mongo from 'mongoose'
import crypt from 'bcryptjs'

const User = new mongo.Schema({
  username: {type: String, unique: true, required: true},
  password: {type: String, select: false, required: true}
  // token: {type: String}
})
//
User.pre('save', (next) => {
  console.log(this);
  if (this.isModified('password') || this.isNew) {
    crypt.genSalt(10, (err, salt) => {
      if (err) {
        next(err)
      } else {
        crypt.hash(user.password, salt, (err, hash) => {
          if (err) {
            next(err)
          } else {
            user.password = hash
            next()
          }
        })
      }
    })
  } else {
    next()
  }
})

export default mongo.model('User', User)

๋ฌด์—‡์ด ์˜ค๋ฅ˜์ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๊นŒ?
PS: ํ”„๋ฆฌํ›…์ด ์‚ฌ์šฉ๋˜์ง€ ์•Š์„ ๋•Œ ์ •์ƒ์ ์œผ๋กœ ์ €์žฅ๋ฉ๋‹ˆ๋‹ค.

๊ฐ€์žฅ ์œ ์šฉํ•œ ๋Œ“๊ธ€

ES6์˜ Fat arrow๋Š” this ๋ฅผ ์–ดํœ˜ ๋ฒ”์œ„์— ๋ฐ”์ธ๋”ฉํ•ฉ๋‹ˆ๋‹ค . ์ด๋Š” ํ™”์‚ดํ‘œ ํ•จ์ˆ˜ ๋‚ด๋ถ€์˜ this ๊ฐ€ ํ™”์‚ดํ‘œ ํ•จ์ˆ˜ ์™ธ๋ถ€์™€ ๋™์ผํ•˜๋‹ค๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•˜๋Š” ๋ฉ‹์ง„ ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค. ๋Œ€์‹  User.pre('save', function(next) {}); ์‚ฌ์šฉํ•˜์‹ญ์‹œ์˜ค.

๋ชจ๋“  3 ๋Œ“๊ธ€

ES6์˜ Fat arrow๋Š” this ๋ฅผ ์–ดํœ˜ ๋ฒ”์œ„์— ๋ฐ”์ธ๋”ฉํ•ฉ๋‹ˆ๋‹ค . ์ด๋Š” ํ™”์‚ดํ‘œ ํ•จ์ˆ˜ ๋‚ด๋ถ€์˜ this ๊ฐ€ ํ™”์‚ดํ‘œ ํ•จ์ˆ˜ ์™ธ๋ถ€์™€ ๋™์ผํ•˜๋‹ค๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•˜๋Š” ๋ฉ‹์ง„ ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค. ๋Œ€์‹  User.pre('save', function(next) {}); ์‚ฌ์šฉํ•˜์‹ญ์‹œ์˜ค.

ํ™”์‚ดํ‘œ ํ•จ์ˆ˜๋กœ ๊ฐ์ฒด๋ฅผ ์–ป๋Š” ๋ฐฉ๋ฒ•์ด ์—†์„๊นŒ์š”?, ์ €๋Š” 'ํ•จ์ˆ˜'๋ฅผ ์‚ฌ์šฉํ•˜์ง€๋งŒ ์Šคํƒ€์ผ ๊ฐ€์ด๋“œ๊ฐ€ ํ”„๋กœ์ ํŠธ์— ๋ถ€๊ณผ๋ฉ๋‹ˆ๋‹ค.

๋ถˆํ–‰ํžˆ๋„ atm์€ ์•„๋‹ˆ์ง€๋งŒ ์‚ฌ์ „ ํ›„ํฌ๋Š” ๋งค๊ฐœ๋ณ€์ˆ˜๊ฐ€ ์•„๋‹Œ this ํ†ตํ•ด ๋ฌธ์„œ๋ฅผ ์ „๋‹ฌํ•˜๋Š” ๋ฐ ๋ช…์‹œ์ ์œผ๋กœ ์˜์กดํ•ฉ๋‹ˆ๋‹ค. ๋šฑ๋šฑํ•œ ํ™”์‚ด์€ ์ด ํŒจ๋Ÿฌ๋‹ค์ž„์—์„œ ์ž‘๋™ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

์ด ํŽ˜์ด์ง€๊ฐ€ ๋„์›€์ด ๋˜์—ˆ๋‚˜์š”?
0 / 5 - 0 ๋“ฑ๊ธ‰