expressServer/models/user.model.js
LingandRX cfe9f92013 feat: 重构项目并添加 MongoDB 支持
- 新增 Prettier 配置文件,规范代码格式
- 重构用户控制器和 DAO 层代码,提高可读性和维护性
- 添加 MongoDB 数据库配置和连接逻辑
- 更新用户模型,使用 Mongoose Schema 定义
- 新增密码加密功能
- 删除 SQLite 相关代码和数据库文件
2024-12-23 23:10:22 +08:00

36 lines
1.2 KiB
JavaScript

const mongoose = require('mongoose')
const bcrypt = require('bcrypt')
const Schema = mongoose.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, index: true },
password: { type: String, required: true, maxlength: 100, set: hashPassword },
email: { type: String, maxlength: 255, index: true },
phone: { type: String, maxlength: 11 },
register_date: { type: Date, default: Date.now },
last_login_date: { type: Date, default: Date.now },
status: { type: String, enum: ['active', 'inactive', 'pending'], default: 'pending' }
})
function hashPassword(password) {
return bcrypt.hash(password, 10)
}
UserSchema.pre('save', async function (next) {
const user = this
if (!user.isModified('password')) return next()
try {
const hashedPassword = await hashPassword(user.password)
user.password = hashedPassword
next()
} catch (error) {
next(error)
}
})
module.exports = mongoose.model('User', UserSchema)