jmo*_*789 3 schema mongoose mongodb node.js
我正在尝试在我正在构建的应用程序中散列密码,并且当我通过调用此函数(coffeesctipt)创建用户时它们正在散列:
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
Run Code Online (Sandbox Code Playgroud)
但是当我做更新并且有这个时:
UserSchema.pre 'findOneAndUpdate', (next) ->
user = this
hashPass(user, next)
Run Code Online (Sandbox Code Playgroud)
我得到的是,TypeError: user.isModified is not a function如果我控制日志用户在预先保存预先记录我正在更新的用户,findandupdate pre不会,id在那里访问pre中的文件或者我需要以另一种方式执行此操作吗?
您收到错误,因为箭头函数会更改"this"的范围.只是用
UserSchema.pre('save', function(next){})
Run Code Online (Sandbox Code Playgroud)
我在打字稿上遇到了类似的问题,事实证明这与您也在使用的箭头运算符有关。现在不知道如何在咖啡脚本中更改此设置,但我认为这应该可以解决您的问题。
你必须改变这一行:
hashPass = (user, next) ->
Run Code Online (Sandbox Code Playgroud)
看看这个: https: //github.com/Automattic/mongoose/issues/4537
| 归档时间: |
|
| 查看次数: |
3746 次 |
| 最近记录: |