繁体   English   中英

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

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

这是我的用户模型:

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

当我保存用户时,它返回空对象并且它不保存也不工作。 我不知道该怎么办? 问题是什么?

您应该在预保存中间件中使用函数形式而不是箭头函数。 因为箭头函数不绑定自己的 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