import mongoose, { Document, Schema } from 'mongoose'; import bcrypt from 'bcrypt'; export interface IUser extends Document { email: string; password: string; refreshToken: string | null; createdAt: Date; updatedAt: Date; comparePassword(candidatePassword: string): Promise; } const userSchema = new Schema( { email: { type: String, required: true, unique: true, lowercase: true, trim: true, }, password: { type: String, required: true, minlength: 6, }, refreshToken: { type: String, default: null, }, }, { timestamps: true, } ); userSchema.pre('save', async function (next) { if (!this.isModified('password')) return next(); const salt = await bcrypt.genSalt(10); this.password = await bcrypt.hash(this.password, salt); next(); }); userSchema.methods.comparePassword = async function ( candidatePassword: string ): Promise { return bcrypt.compare(candidatePassword, this.password); }; userSchema.methods.toJSON = function () { const obj = this.toObject(); delete obj.password; delete obj.refreshToken; return obj; }; const User = mongoose.model('User', userSchema); export default User;