【发布时间】:2017-03-02 20:50:49
【问题描述】:
我正在尝试在我正在构建的应用程序中对密码进行哈希处理,当我通过调用此函数 (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
但是当我进行更新并拥有此预置时:
UserSchema.pre 'findOneAndUpdate', (next) ->
user = this
hashPass(user, next)
我得到TypeError: user.isModified is not a function 如果我在 pres 控制台登录用户保存 pre 记录我正在更新的用户,findandupdate pre 没有,id 有办法访问 pres 中的文档还是我需要这样做另一种方式?
【问题讨论】:
-
我遇到了同样的问题,但我的问题是在尝试 User.Create 和 new User({}) 然后 user.save()
-
我认为你的问题是
.pre('update')钩子中的this指的是Query对象而不是模型本身:mongoosejs.com/docs/middleware.html#notes
标签: node.js mongodb mongoose schema