File size: 1,282 Bytes
1a81036 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | import mongoose from 'mongoose';
import bcrypt from 'bcryptjs';
const userSchema = new mongoose.Schema({
name: { type: String, required: true, trim: true },
email: { type: String, required: true, unique: true, lowercase: true, trim: true },
password: { type: String, required: true, minlength: 6 },
role: { type: String, enum: ['admin', 'staff', 'customer'], default: 'customer' },
phone: { type: String, trim: true },
isActive: { type: Boolean, default: true },
lastLogin: { type: Date },
// Customer specific
loyaltyPoints: { type: Number, default: 0 },
orderHistory: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Order' }],
// Notification prefs
notifyRestock: { type: Boolean, default: true },
notifyOrderReady: { type: Boolean, default: true },
}, { timestamps: true });
userSchema.pre('save', async function (next) {
if (!this.isModified('password')) return next();
this.password = await bcrypt.hash(this.password, 12);
next();
});
userSchema.methods.comparePassword = async function (candidatePassword) {
return bcrypt.compare(candidatePassword, this.password);
};
userSchema.methods.toSafeObject = function () {
const obj = this.toObject();
delete obj.password;
return obj;
};
export default mongoose.model('User', userSchema);
|