samlax12's picture
Upload 18 files
006ee19 verified
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const userSchema = new mongoose.Schema(
{
username: {
type: String,
required: [true, '请输入用户名'],
unique: true,
trim: true,
},
password: {
type: String,
required: [true, '请输入密码'],
minlength: [6, '密码长度不能小于6个字符'],
},
isAdmin: {
type: Boolean,
default: false,
},
},
{
timestamps: true,
}
);
// 密码匹配方法
userSchema.methods.matchPassword = async function (enteredPassword) {
try {
return await bcrypt.compare(enteredPassword, this.password);
} catch (error) {
console.error('密码比较出错:', error);
return false;
}
};
// 保存前加密密码
userSchema.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);
next();
} catch (error) {
next(error);
}
});
const User = mongoose.model('User', userSchema);
module.exports = User;