Attempting to hash a password using the .pre()
hook:
import * as bcrypt from 'bcrypt'; // "bcrypt": "^1.0.2"
(<any>mongoose).Promise = require('bluebird');
const user_schema = new Schema({
email: { type: String, required: true },
password: { type: String, required: true },
})
const SALT_WORK_FACTOR = 10;
user_schema.pre('save', function (next) {
const user = this;
if (!user.isModified('password')) return next();
bcrypt.hash(user.password, SALT_WORK_FACTOR, function (error, hash) {
if (error) return next(error);
user.password = hash;
console.log(hash); // properly consoles the hash
next();
});
});
The hash value is successfully printed to the console, indicating it's being generated correctly. However, when trying to save like below:
const x = new MongoUser({
'_id': mongoose.Types.ObjectId(),
'email': '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f88c9d8b8cb88c9d8b8cd69b979">[email protected]</a>',
'password': 'testp@$$word',
})
console.log(x); // object is logged properly
x.save(function(err: any){
console.log('callback fired'); // this does not log
if (err) console.log(err)
});
The save()
callback is never triggered.
I can confirm that removing the .pre90
hook or replacing bcrypt.hash()
with next()
allows saving an unhashed password successfully. So, I am certain about the schema setup and database connection.
Reason for save()
not triggering?
Not a race condition as files are tested before running a separate execution script.