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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| const mongoose = require('mongoose'); const bcrypt = require('bcryptjs');
const userSchema = new mongoose.Schema({ name: { type: String, required: [true, '用户名不能为空'], trim: true, minlength: [2, '用户名至少 2 个字符'], maxlength: [50, '用户名最多 50 个字符'], }, email: { type: String, required: [true, '邮箱不能为空'], unique: true, lowercase: true, match: [/^\S+@\S+\.\S+$/, '邮箱格式不正确'], }, password: { type: String, required: [true, '密码不能为空'], minlength: [6, '密码至少 6 位'], select: false, }, role: { type: String, enum: ['user', 'admin'], default: 'user', }, isActive: { type: Boolean, default: true, }, }, { timestamps: true, toJSON: { transform(doc, ret) { ret.id = ret._id.toString(); delete ret._id; delete ret.__v; delete ret.password; return ret; }, }, });
userSchema.pre('save', async function(next) { if (!this.isModified('password')) return next(); this.password = await bcrypt.hash(this.password, 12); next(); });
userSchema.methods.comparePassword = async function(candidatePassword) { return bcrypt.compare(candidatePassword, this.password); };
module.exports = mongoose.model('User', userSchema);
|