45 lines
985 B
JavaScript
45 lines
985 B
JavaScript
const mongoose = require('mongoose');
|
|
const bcrypt = require('bcryptjs');
|
|
|
|
const adminSchema = new mongoose.Schema({
|
|
username: {
|
|
type: String,
|
|
required: true,
|
|
unique: true,
|
|
trim: true
|
|
},
|
|
email: {
|
|
type: String,
|
|
trim: true,
|
|
lowercase: true,
|
|
sparse: true // allows null/undefined without unique-index collisions
|
|
},
|
|
password: {
|
|
type: String,
|
|
required: true,
|
|
minlength: 12
|
|
}
|
|
}, {
|
|
timestamps: true
|
|
});
|
|
|
|
// Hash password before saving
|
|
adminSchema.pre('save', async function(next) {
|
|
if (!this.isModified('password')) return next();
|
|
|
|
try {
|
|
const salt = await bcrypt.genSalt(12);
|
|
this.password = await bcrypt.hash(this.password, salt);
|
|
next();
|
|
} catch (error) {
|
|
next(error);
|
|
}
|
|
});
|
|
|
|
// Method to compare password
|
|
adminSchema.methods.comparePassword = async function(candidatePassword) {
|
|
return await bcrypt.compare(candidatePassword, this.password);
|
|
};
|
|
|
|
module.exports = mongoose.model('Admin', adminSchema);
|