Spaces:
Sleeping
Sleeping
File size: 1,001 Bytes
4c025e9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
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; |