简体   繁体   English

如何在节点 js 和 mongoose 中保存用户之前散列密码

[英]How to hash password before saving user in node js and mongoose

this is my user model:这是我的用户模型:

const schema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    min: 6,
    max: 255
  },
  email: {
    type: String,
    required: true,
    min: 6,
    max: 255
  },
  password: {
    type: String,
    required: true,
    max: 1024,
    min: 6
  }
});

schema.pre("save", async next => {
  if (!this.isModified("password")) return next();
  try {
    const salt = await bcrypt.genSalt(10);
    this.password = await bcrypt.hash(this.password, salt);
    return next();
  } catch (error) {
    return next(erro);
  }
});

module.exports = mongoose.model("User", schema);

when i save user, it return empty object and it doesn't save and not working.当我保存用户时,它返回空对象并且它不保存也不工作。 i don't know what should to do?我不知道该怎么办? what is the problem?问题是什么?

You should use function form instead of arrow function inside the pre save middleware.您应该在预保存中间件中使用函数形式而不是箭头函数。 Because Arrow functions do not bind their own this.因为箭头函数不绑定自己的 this。

schema.pre("save", async function(next) {
  if (!this.isModified("password")) return next();
  try {
    const salt = await bcrypt.genSalt(10);
    this.password = await bcrypt.hash(this.password, salt);
    return next();
  } catch (error) {
    return next(error);
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM