Skip to content

Instantly share code, notes, and snippets.

@wsfuller
Last active October 19, 2016 04:25
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 wsfuller/a2ec36f38056ca7f592b857777fa0f07 to your computer and use it in GitHub Desktop.
Save wsfuller/a2ec36f38056ca7f592b857777fa0f07 to your computer and use it in GitHub Desktop.
var mongoose = require('mongoose');
// User Schema
var userSchema = mongoose.Schema({
email:{
type: String,
required: true,
unique: true
},
password:{
type: String,
required: true
},
createdAt:{
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('User', userSchema);
userSchema.pre('save', function(next) {
var newUser = this;
console.log('password 1: ', this.password);
console.log('newUser.password 1: ', newUser.password);
// only hash the password if it has been modified (or is new)
if (!this.isModified('password')) {
return next();
}
// generate a salt
return bcrypt.genSalt(10, function(error, salt) {
console.log('password 2: ', this.password);
console.log('newUser.password 2: ', newUser.password);
if (error) {
return next(error);
}
// hash the password using the new salt
return bcrypt.hash(newUser.password, salt, function(error, hash) {
console.log('password 3: ' + this.password);
console.log('newUser.password 3: ', newUser.password);
if (error) {
return next(error);
}
// override the cleartext password with the hashed one
newUser.password = hash;
console.log('hash user password: ', newUser.password);
return next();
});
});
});
@wsfuller
Copy link
Author

Running console log at user schema 3 line 37, this.password is undefined

@sbaidon
Copy link

sbaidon commented Oct 19, 2016

what if you run console.log(this) ?

@wsfuller
Copy link
Author

Looks like the this.password is out of scope in the return function. So just made a new object and passing that through is working as expected.

@wsfuller
Copy link
Author

Line 50, never returns a promise back to the routes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment