Skip to content

Instantly share code, notes, and snippets.

@chanakaDe
Created October 19, 2015 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chanakaDe/315743d9c29e4ba25958 to your computer and use it in GitHub Desktop.
Save chanakaDe/315743d9c29e4ba25958 to your computer and use it in GitHub Desktop.
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var Schema = mongoose.Schema;
/**
* Creating user schema.
* @type {*|Schema}
*/
var UserSchema = new Schema({
name: String,
username: {type: String, required: true, index: {unique: true}},
password: {type: String, required: true, select: false}
});
/**
* Encrypting the user password.
*/
UserSchema.pre('save', function (next) {
var user = this;
if (!user.isModified('password')) return next();
bcrypt.hash(user.password, null, null, function (err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
});
UserSchema.methods.comparePassword = function (password) {
var user = this;
return bcrypt.compareSync(password, user.password);
};
module.exports = mongoose.model('User', UserSchema);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment