samlax12's picture
Upload 19 files
4c025e9 verified
raw
history blame
1 kB
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) {
return await bcrypt.compare(enteredPassword, this.password);
};
// 保存前加密密码
userSchema.pre('save', async function (next) {
if (!this.isModified('password')) {
next();
}
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
});
const User = mongoose.model('User', userSchema);
module.exports = User;