使用 bcrypt 时对象未定义

Object is undefined while using bcrypt

我正在尝试对密码进行哈希处理,但我绑定该函数的对象未定义。为什么这样?如何解决?

路线:

app.post('/users',(req,res)=>{
  let user = new User();
  user.username = req.body.username;
  user.password = req.body.password;
  user.email = req.body.email;
  user.save((err)=>{
    if(err)
   res.send('Username or email already exists');
   else
   res.send("User Created Successfully")
  }); //through mongooose
})

Bcrypt 函数 && mongoose 中间件

UserSchema.pre('save',(next)=>{
  let currentUser = this;
  console.log(currentUser.username); //getting undefined here
  bcrypt.hash(currentUser.password,null,null,(err,hash)=>{
    if(err) return next(err);
   currentUser.password = hash;
   next();

  })
})

不要使用 es6 arrow-function,而是使用如下匿名函数:

UserSchema.pre('save',function(next){
   let currentUser = this;
  console.log(currentUser.username); //getting undefined here
  bcrypt.hash(currentUser.password,null,null,(err,hash)=>{
    if(err) return next(err);
    currentUser.password = hash;
    next();
  })  
})

当您使用箭头函数时,this 将不是用户对象,而是架构对象。

尝试以下使用async/await加密密码的方法:

userSchema.pre('save', async function save(next) {
  try {
    const hash = await bcrypt.hash(this.password, 10);
    this.password = hash;
    return next();
  } catch (error) {
    return next(error);
  }  
})