- 更新导入路径,使用 .js 后缀 -修正用户模型中的密码加密和验证逻辑 - 优化用户路由和控制器 - 重构用户服务和仓库,使用原生 mongoose 方法- 更新错误处理和日志记录
38 lines
1.3 KiB
JavaScript
38 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'))
|
|
}
|
|
})
|
|
|
|
// 更新 lastLoginDate 在用户登录时
|
|
UserSchema.methods.updateLastLoginDate = function () {
|
|
this.lastLoginDate = new Date()
|
|
}
|
|
|
|
export default model('User', UserSchema)
|