import mongoose from 'mongoose' import bcrypt from 'bcrypt' const UserSchema = new mongoose.Schema({ name: { type: String, trim: true, required: 'Name is required' }, email: { type: String, trim: true, unique: 'Email is already exists', match: [/.+\@.+\..+/, 'Please fill a valid email address'], required: 'Email is required' }, created: { type: Date, default: Date.now, }, updated: Date, hashedPassword: { type: String, required: 'Password is required' }, salt: String, photo: { data: Buffer, contentType: String, }, instructor: { type: Boolean, default: false, }, }) UserSchema.virtual('password') .set(function (password) { this._password = password this.salt = bcrypt.genSaltSync() this.hashedPassword = bcrypt.hashSync(password, this.salt) }) .get(() => { return this._password }) UserSchema.methods.authenticate = function (plainText) { return bcrypt.compareSync(plainText, this.hashedPassword) } UserSchema.path('hashedPassword').validate(function (value) { if (this._password && this._password.length < 6) { this.invalidate('password', 'Password must be at least 6 characters.') } if (this.isNew && !this._password) { this.invalidate('password', 'Password is required') } }) export default mongoose.model('User', UserSchema)