2024-07-10 23:40:46 +03:00

56 lines
1.0 KiB
JavaScript

// users.js
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const userSchema = new mongoose.Schema({
_id: {
type: String,
required: true,
},
username: {
type: String,
required: true,
unique: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
role: {
type: String,
enum: ['user', 'admin'],
default: 'user',
},
createdAt: {
type: Date,
default: Date.now,
},
updatedAt: {
type: Date,
default: Date.now,
},
});
// Hash password before saving
userSchema.pre('save', async function(next) {
const user = this;
if (user.isModified('password')) {
user.password = await bcrypt.hash(user.password, 10);
}
next();
});
// Compare password for login
userSchema.methods.comparePassword = async function(candidatePassword) {
const user = this;
return await bcrypt.compare(candidatePassword, user.password);
};
const User = mongoose.model('User', userSchema);
module.exports = User;