Created
October 2, 2019 14:30
-
-
Save muddokon/391617a66b863e4bdc357d91c8fd3d5e to your computer and use it in GitHub Desktop.
User.model.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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