UNPKG

setup-mern

Version:

A CLI tool to generate a MERN backend boilerplate in seconds!

37 lines (33 loc) 1.01 kB
const mongoose = require('mongoose'); const validator = require('validator'); const bcrypt = require('bcryptjs'); const userSchema = new mongoose.Schema({ name: { type: String, required: [true, 'Please provide a name'], }, email: { type: String, required: [true, 'Please provide an email'], unique: true, lowercase: true, validate: [validator.isEmail, 'Please provide a valid email'], }, password: { type: String, required: [true, 'Please provide a password'], minlength: 8, select: false, }, }); // Hash password before saving userSchema.pre('save', async function (next) { if (!this.isModified('password')) return next(); this.password = await bcrypt.hash(this.password, 12); next(); }); // Compare passwords userSchema.methods.comparePassword = async function (candidatePassword) { return await bcrypt.compare(candidatePassword, this.password); }; module.exports = mongoose.model('User', userSchema);