import mongoose from 'mongoose' import bcrypt from 'bcrypt' const UserSchema = new mongoose.Schema( { username: { type: String, required: true, unique: true, index: true, }, nickname: { type: String, }, password: { type: String, required: true, }, role: { type: String, enum: ['admin', 'user'], default: 'user', }, }, { timestamps: true } ) // 保存前自动对密码进行哈希加密 UserSchema.pre('save', async function () { this.password = await bcrypt.hash(this.password, 10) }) // 实例方法:校验密码 UserSchema.methods.comparePassword = async function (candidatePassword) { return bcrypt.compare(candidatePassword, this.password) } // 输出时始终不返回密码 UserSchema.methods.toJSON = function () { const obj = this.toObject() delete obj.password return obj } const User = mongoose.model('User', UserSchema) export default User