Skip to content

Instantly share code, notes, and snippets.

@sanath-kumar
Created January 16, 2019 15:41
Show Gist options
  • Save sanath-kumar/8808ced5d6ff50294ad7702df563484f to your computer and use it in GitHub Desktop.
Save sanath-kumar/8808ced5d6ff50294ad7702df563484f to your computer and use it in GitHub Desktop.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt-nodejs');
const UserSchema = new Schema({
email : {
type : String,
unique : true
},
username: String,
password: String,
});
UserSchema.pre('save', function (next) {
var user = this;
if (this.isModified('password') || this.isNew) {
bcrypt.genSalt(10, function (err, salt) {
if (err) {
return next(err);
}
bcrypt.hash(user.password, salt, null, function (err, hash) {
if (err) {
return next(err);
}
user.password = hash;
next();
});
});
} else {
return next();
}
});
UserSchema.methods.comparePassword = function (pwd, cb) {
bcrypt.compare(pwd, this.password, function (err, isMatch) {
if (err) {
return cb(err);
}
cb(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