我使用 bcryptjs 在存储到 mongodb 之前对密码进行哈希处理,但它将密码存储为明文(无哈希)。这是我的 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")) {
next();
}
const salt = await bcrypt.genSalt(10);
this.password = bcrypt.hash(this.password, salt);
});
const User = mongoose.model("User", userSchema);
module.exports = User;
我的注册控制器是这样写的
module.exports.register = asynchandler(async (req, res) => {
const { mobile, password } = req.body;
const user = await User.findOne({ mobile });
if (user) {
res.status(400).json({ message: "user already exists" });
} else {
const newUser = await User.create({
mobile,
password,
});
res.status(200).json(newUser);
}
});
我终于找到了解决方案。我不知道为什么但是使用下面的代码工作正常
userSchema.pre("save", async function (next) {
if (!this.isModified("password")) {
next();
}
bcrypt.hash(this.password, 10, (err, hash) => {
if (err) {
console.log("something went wrong for hashing");
}
if (hash) {
this.password = hash;
}
});
});
你不需要在注册控制器中添加密码,
module.exports.register = asynchandler(async (req, res) => {
const { mobile, password } = req.body;
const user = await User.findOne({ mobile });
if (user) {
res.status(400).json({ message: "user already exists" });
} else {
const newUser = await User.create({
mobile,
});
res.status(200).json(newUser);
}
});