使用bcryptjs加密密码存入MongoDB失败,密码以明文存储
密码未哈希存储的问题修复
你的代码里有两个关键错误导致密码以明文存储:
1. bcrypt.hash未使用异步等待
bcrypt.hash()是异步函数,直接赋值会让this.password成为一个Promise对象,而非哈希后的密码字符串。mongoose无法正确解析这个Promise,最终存储的是原始明文密码。
2. pre-save钩子未终止后续代码执行
当密码未修改时,调用next()后没有返回,导致后续哈希代码仍会执行,可能引发意外问题,同时也影响正常哈希逻辑的执行。
修复后的userModel.js代码
const mongoose = require("mongoose"); const bcrypt = require("bcryptjs"); const userSchema = new mongoose.Schema( { mobile: { type: String, }, password: { type: String, }, }, { timestamps: true } ); userSchema.methods.matchPassword = async function (enteredPassword) { return await bcrypt.compare(enteredPassword, this.password); }; userSchema.pre("save", async function (next) { console.log("pre save called"); if (!this.isModified("password")) { return next(); // 添加return终止后续代码执行 } const salt = await bcrypt.genSalt(10); this.password = await bcrypt.hash(this.password, salt); // 添加await获取哈希结果 }); const User = mongoose.model("User", userSchema); module.exports = User;
验证说明
修复后,当调用User.create()创建用户时,pre-save钩子会正确执行密码哈希逻辑,MongoDB中存储的将是哈希后的密码字符串。你可以通过Postman再次测试注册接口,然后查看MongoDB数据库确认密码已被哈希。
内容的提问来源于stack exchange,提问作者Aliking66
相关产品推荐
相关产品推荐

