Created
June 14, 2016 20:51
-
-
Save syul/b254b9c743a44656a2f747db8764211b to your computer and use it in GitHub Desktop.
user model
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
'use strict'; | |
const mongoose = require('mongoose'); | |
const Schema = mongoose.Schema; | |
const MD5 = require('crypto-js/md5'); | |
function setPassword(password) { | |
return this.encryptPassword(password); | |
}; | |
function validateUserNameField(userName, cb) { | |
this.model('User').find({ userName: userName }, { _id: 0, userName: 1 }).count((err, val) => { | |
cb(val == 0); | |
}); | |
}; | |
function validateEmailField(email, cb) { | |
this.model('User').find({ email: email }, { _id: 0, email: 1 }).count((err, val) => { | |
cb(val == 0); | |
}); | |
}; | |
const UserSchema = new Schema({ | |
userName: { | |
type: String, | |
required: true, | |
validate: { | |
validator: validateUserNameField, | |
message: 'User with name {VALUE} has been already added.' | |
} | |
}, | |
email: { | |
type: String, | |
required: true, | |
validate: { | |
validator: validateEmailField, | |
message: 'User with email {VALUE} has been already added.' | |
} | |
}, | |
password: { | |
type: String, | |
set: setPassword, | |
required: true | |
}, | |
firstName: { | |
type: String, | |
required: false | |
}, | |
lastName: { | |
type: String, | |
required: false | |
} | |
}); | |
UserSchema.methods.comparePassword = function (password) { | |
return this.password == this.encryptPassword(password); | |
}; | |
UserSchema.methods.encryptPassword = function (password) { | |
return MD5(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