Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Pulling in required dependencies
- const mongoose = require('mongoose');
- const bcrypt = require('bcrypt-nodejs');
- const Schema = mongoose.Schema;
- //Creat UserSchema
- const UserSchema = new Schema({
- local: {
- email: String,
- password: String,
- resetPasswordToken: String,
- resetPasswordExpires: Date
- },
- role: {
- type: String,
- default: 'user',
- },
- books_downloaded: {
- booksId: {
- type: Array,
- required: false,
- },
- },
- books_needed: {
- type: Object,
- default: null,
- },
- created_at: {
- type: Date,
- default: Date.now,
- },
- });
- // methods=====================================================
- // generating a hash
- UserSchema.methods.generateHash = (password) => {
- return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
- }
- //Hashing password on update
- UserSchema.pre('save', function(next) {
- const User = this;
- const SALT_FACTOR = 5;
- if(!User.isModified('local.password')) return next();
- bcrypt.genSalt(SALT_FACTOR, function(err,salt) {
- if(err) return next(err);
- bcrypt.hash(User.local.password, salt, null, function(err,hash) {
- if(err) return next(err);
- User.local.password = hash;
- next();
- });
- });
- });
- // expose User model to the app
- module.exports = mongoose.model('User', UserSchema);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement