Last active
August 11, 2019 19:15
-
-
Save tarusharora/ac8d3d0d140a528b174a8036d525cb53 to your computer and use it in GitHub Desktop.
User model and mongoose
This file contains hidden or 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
const bcrypt = require('bcrypt-nodejs'); | |
const mongoose = require('mongoose'); | |
const userSchema = new mongoose.Schema({ | |
email: { | |
type: String, | |
required: true, | |
unique: true, | |
}, | |
password: String, | |
}); | |
/** | |
* Password hash middleware. | |
*/ | |
userSchema.pre('save', function save(next) { | |
const user = this; | |
if (!user.isModified('password')) { return next(); } | |
bcrypt.genSalt(10, (err, salt) => { | |
if (err) { return next(err); } | |
bcrypt.hash(user.password, salt, null, (err, hash) => { | |
if (err) { return next(err); } | |
user.password = hash; | |
next(); | |
}); | |
}); | |
}); | |
/** | |
* Helper method for validating user's password. | |
*/ | |
userSchema.methods.comparePassword = function comparePassword(candidatePassword) { | |
return new Promise((resolve, reject) => { | |
bcrypt.compare(candidatePassword, this.password, (err, isMatch) => { | |
if (err) { reject(err); } | |
resolve(isMatch); | |
}); | |
}); | |
}; | |
const User = mongoose.model('User', userSchema); | |
module.exports = User; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment