expressServer/models/userModel.js
LingandRX 21e4c3ea8a refactor(user): 重构用户模块代码
- 移除了不必要的 getAllUsers 控制器方法
-重命名 findUserList 为 getUserList,更符合方法的实际功能- 引入 UserDTO 类,用于用户数据传输和验证
- 优化了错误处理和日志记录
- 简化了代码结构,提高了可读性和可维护性
2025-01-05 19:41:03 +08:00

37 lines
1.3 KiB
JavaScript

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'))
}
})
UserSchema.methods.updateLastLoginDate = function () {
this.lastLoginDate = new Date()
}
export default model('User', UserSchema)