我正在尝试在我正在构建的应用程序中散列密码,并且当我通过调用此函数(coffeesctipt)创建用户时它们正在散列: UserSchema.pre 'save', (next) - user = this hashPass(user, next)hashPass = (user, next) - #
UserSchema.pre 'save', (next) -> user = this hashPass(user, next) hashPass = (user, next) -> # only hash the password if it has been modified (or is new) if !user.isModified('password') return next() # generate a salt bcrypt.genSalt SALT_WORK_FACTOR, (err, salt) -> if err return next(err) # hash the password using our new salt bcrypt.hash user.password, salt, (err, hash) -> if err return next(err) # override the cleartext password with the hashed one user.password = hash next() return return
但是当我做更新并且有这个时:
UserSchema.pre 'findOneAndUpdate', (next) -> user = this hashPass(user, next)
我得到TypeError:user.isModified不是一个函数,如果我控制日志用户在预先保存预先记录我正在更新的用户,findandupdate pre不会,id那里可以访问pre中的文件或者我需要另一种方式呢?
您收到错误,因为箭头函数会更改“this”的范围.只是用
UserSchema.pre('save', function(next){})