import { Schema as _Schema, model } from 'mongoose' import { hashPassword } from '../utils/hashUtils.js' const Schema = _Schema const UserSchema = new Schema({ name: { type: String, required: true, maxlength: 100 }, gender: { type: String, enum: ['male', 'female', 'other'], maxlength: 20 }, birth: { type: Date }, avatar: { type: String, maxlength: 100 }, account: { type: String, required: true, unique: true, maxlength: 100 }, password: { type: String, required: true, maxlength: 100 }, email: { type: String, match: /^\S+@\S+\.\S+$/, maxlength: 255, index: true }, phone: { type: String, match: /^1[3-9]\d{9}$/, maxlength: 11 }, registerDate: { type: Date, default: Date.now }, lastLoginDate: { type: Date }, status: { type: String, enum: ['active', 'inactive', 'pending'], default: 'pending' } }) UserSchema.pre('save', async function (next) { const user = this if (!user.isModified('password')) return next() try { user.password = await hashPassword(user.password) next() } catch (error) { // 记录错误日志,避免泄露敏感信息 console.error('Error hashing password:', error.message) next(new Error('Failed to hash password')) } }) // 更新 lastLoginDate 在用户登录时 UserSchema.methods.updateLastLoginDate = function () { this.lastLoginDate = new Date() } export default model('User', UserSchema)