Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '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);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement