在mongoose中进行预更新时,user.isModified不是函数

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中的文件或者我需要以另一种方式执行此操作吗?

llo*_*ola 8

您收到错误,因为箭头函数会更改"this"的范围.只是用

UserSchema.pre('save', function(next){})
Run Code Online (Sandbox Code Playgroud)


orl*_*aqp 1

我在打字稿上遇到了类似的问题,事实证明这与您也在使用的箭头运算符有关。现在不知道如何在咖啡脚本中更改此设置,但我认为这应该可以解决您的问题。

你必须改变这一行:

hashPass = (user, next) ->
Run Code Online (Sandbox Code Playgroud)

看看这个: https: //github.com/Automattic/mongoose/issues/4537

  • 我确实检查过,咖啡中的 `UserSchema.pre 'findOneAndUpdate', (next) ->` 编译为 `UserSchema.pre('findOneAndUpdate', function(next) {` 所以我的代码中几乎没有什么可以更改的使其基于该解决方案工作。我的问题是由于 Model.pre 'findOneAndUpdate' 返回的 'this' 与 Model.pre 'save' 不同。pre 'save' 将用户返回为 'this'而 findOneAndUpdate 上的 pre 则没有。 (4认同)