Last active
October 19, 2016 04:25
-
-
Save wsfuller/a2ec36f38056ca7f592b857777fa0f07 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}); | |
}); | |
}); |
what if you run console.log(this) ?
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.
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
Running console log at user schema 3 line 37, this.password is undefined