'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) {});
์ฌ์ฉํ์ญ์์ค.
ํ์ดํ ํจ์๋ก ๊ฐ์ฒด๋ฅผ ์ป๋ ๋ฐฉ๋ฒ์ด ์์๊น์?, ์ ๋ 'ํจ์'๋ฅผ ์ฌ์ฉํ์ง๋ง ์คํ์ผ ๊ฐ์ด๋๊ฐ ํ๋ก์ ํธ์ ๋ถ๊ณผ๋ฉ๋๋ค.
๋ถํํ๋ atm์ ์๋์ง๋ง ์ฌ์ ํํฌ๋ ๋งค๊ฐ๋ณ์๊ฐ ์๋ this
ํตํด ๋ฌธ์๋ฅผ ์ ๋ฌํ๋ ๋ฐ ๋ช
์์ ์ผ๋ก ์์กดํฉ๋๋ค. ๋ฑ๋ฑํ ํ์ด์ ์ด ํจ๋ฌ๋ค์์์ ์๋ํ์ง ์์ต๋๋ค.
๊ฐ์ฅ ์ ์ฉํ ๋๊ธ
ES6์ Fat arrow๋
this
๋ฅผ ์ดํ ๋ฒ์์ ๋ฐ์ธ๋ฉํฉ๋๋ค . ์ด๋ ํ์ดํ ํจ์ ๋ด๋ถ์this
๊ฐ ํ์ดํ ํจ์ ์ธ๋ถ์ ๋์ผํ๋ค๋ ๊ฒ์ ์๋ฏธํ๋ ๋ฉ์ง ๋ฐฉ๋ฒ์ ๋๋ค. ๋์User.pre('save', function(next) {});
์ฌ์ฉํ์ญ์์ค.