预保存挂钩存在问题,其中 '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:不使用pre hook时正常保存。
ES6 中的胖箭头将this
绑定到词法作用域,这只是一种奇特的说法,即箭头函数内部的this
与箭头函数外部的相同。 请改用User.pre('save', function(next) {});
。
有没有办法用箭头函数获取对象?,我会使用“函数”,但在项目中强加了样式指南。
不幸的是不是 atm,预挂钩明确地依赖于通过this
而不是作为参数传递文档。 粗箭头不适用于这种范式。
最有用的评论
ES6 中的胖箭头将
this
绑定到词法作用域,这只是一种奇特的说法,即箭头函数内部的this
与箭头函数外部的相同。 请改用User.pre('save', function(next) {});
。