Skip to content

Instantly share code, notes, and snippets.

@gecko-8
Created August 20, 2019 19:44
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 gecko-8/682f850ca0999a49dce9fc3190d21561 to your computer and use it in GitHub Desktop.
Save gecko-8/682f850ca0999a49dce9fc3190d21561 to your computer and use it in GitHub Desktop.
User model file for Udemy Node Course
const mongoose = require('mongoose');
const validator = require('validator');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
unique: true, // Email can only be used once
required: true,
trim: true,
lowercase: true,
validate(value) {
if (!validator.isEmail(value))
throw new Error('Email is invalid');
}
},
age: {
type: Number,
default: 0,
validate(value) {
if (value < 0) {
throw new Error('Age must be a positive number');
}
}
},
password: {
type: String,
required: true,
minlength: 7,
trim: true,
validate(value) {
if (value.toLowerCase().includes('password'))
throw new Error('Your password cannot include the word "password" in any form')
}
},
tokens: [{
token: {
type: String,
required: true
}
}]
});
// Methods available on instances
userSchema.methods.generateAuthToken = async function() {
const user = this;
const token = jwt.sign({ _id: user._id.toString() }, 'thisismykey');
user.tokens = user.tokens.concat({ token });
await user.save();
return token;
};
// Statics available on model
userSchema.statics.findByCredentials = async function(email, password) {
const user = await this.findOne({ email });
if (!user)
throw new Error('Unable to login');
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch)
throw new Error('Unable to login');
return user;
};
// Hash the plain text password before saving
userSchema.pre('save', async function(next) {
const user = this;
if (user.isModified('password'))
user.password = await bcrypt.hash(user.password, 8);
console.log('Just before saving');
next();
});
module.exports = mongoose.model('User', userSchema);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment