使用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不会是用户对象时,它将是架构对象。

尝试下面使用异步/等待加密密码的方法:

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);
  }  
})

相关内容

最新更新