expressServer/models/userModel.js

34 lines
1.1 KiB
JavaScript

const mongoose = require('mongoose')
const { hashPassword } = require('../utils/hashUtils')
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 },
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' }
})
UserSchema.pre('save', async function (next) {
const user = this
if (!user.isModified('password')) return next()
try {
console.log(user.password)
const hashedPassword = await hashPassword(user.password)
user.password = hashedPassword
next()
} catch (error) {
next(error)
}
})
module.exports = mongoose.model('User', UserSchema)