I am creating a user model for an app. My user schema is this:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt-nodejs');
SALT_WORK_FACTOR = 10;
const userSchema = Schema({
email:{type: String, required: true},
encrypted_password:{type: String, required: true},
reset_password_token:{type: String},
reset_password_sent_at:{type: Date},
sign_in_count:{type: Number},
current_sign_in_at:{type: Date},
last_sign_in_at:{type: Date},
current_sign_in_ip:{type: String},
last_sign_in_ip:{type: String},
active:{type: Boolean},
role_id:[{ type: Schema.Types.ObjectId, ref: 'roles' ,required: true}],
create_date:{type: Date, default: Date.now},
});
This is my create method:
module.exports.insert = (user, callback) => {
User.create(user,callback);
}
I add this function to hashing the password, but doesn't work:
User.pre('create', function(next) {
var user = this;
// only hash the password if it has been modified (or is new)
if (!user.isModified('encrypted_password')) return next();
// generate a salt
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if (err) return next(err);
// hash the password using our new salt
bcrypt.hash(user.encrypted_password, salt, function(err, hash) {
if (err) return next(err);
// override the cleartext password with the hashed one
user.encrypted_password = hash;
next();
});
});
});
I get the error
User.pre is not a function.
How can I store a encrypted password using the create function to save the data.
Thanks in advance
via joselegit
No comments:
Post a Comment