Can anyone figure out what's wrong with my code below?
From documentation it looks like the this
in Mongoose .pre('save')
method should be the model itself, but in my code below this
ends up being an empty object.
const Mongoose = require('./lib/database').Mongoose;
const Bcrypt = require('bcrypt');
const userSchema = new Mongoose.Schema({
email: { type: String, required: true, index: { unique: true } },
password: { type: String, required: true }
});
userSchema.pre('save', (next) => {
const user = this;
Bcrypt.genSalt((err, salt) => {
if (err) {
return next(err);
}
Bcrypt.hash(user.password, salt, (err, encrypted) => {
if (err) {
return next(err);
}
user.password = encrypted;
next();
});
});
});
const User = Mongoose.model('User', userSchema);
When saving a user, I get the following error [Error: data and salt arguments required]
.
function createUser(email, password, next) {
const user = new User({
email: email,
password: password
});
user.save((err) => {
if (err) {
return next(err);
}
return next(null, user);
});
}
createUser('test@email.com', 'testpassword', (err, user) => {
if (err) {
console.log(err);
}
else {
console.log(user);
}
process.exit();
});
If I remove the .pre('save')
then it saves fine of course. Version of Mongoose I'm using is 4.2.6.