Skip to content

Instantly share code, notes, and snippets.

@muddokon
Created October 2, 2019 14:30
Show Gist options
  • Save muddokon/391617a66b863e4bdc357d91c8fd3d5e to your computer and use it in GitHub Desktop.
Save muddokon/391617a66b863e4bdc357d91c8fd3d5e to your computer and use it in GitHub Desktop.
User.model.js
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs')
var userSchema = new mongoose.Schema({
name: String,
email: {type:String,unique:true},
password: String,
avatar:String
},{timestamps:true})
userSchema.pre('save', next => {
var user = this;
if (!user.isModified('password')) {return next()};
bcrypt.hash(user.password,10).then((hashedPassword) => {
user.password = hashedPassword;
next();
})
}, function (err) {
next(err)
})
userSchema.methods.comparePassword=function(candidatePassword,next){ bcrypt.compare(candidatePassword,this.password,function(err,isMatch){
if(err) return next(err);
next(null,isMatch)
})
}
module.exports = mongoose.model("user", userSchema);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment