1
I have the following model, where when registering the user in mongodb
, I want him to encrypt the password using bcryptjs
, using the Mongoose method UserSchema.pre('save'...
const bcrypt = require('bcryptjs');
module.exports = (app) => {
const mongoose = app.config.banco;
const UserSchema = new mongoose.Schema({
nome: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true,
select: false
},
criacao: {
type: Date,
default: Date.now
}
});
UserSchema.pre('save', async (next) => {
console.log(this);
const hash = await bcrypt.hash(this.password, 10);
this.password = hash;
next();
});
const user = mongoose.model('User', UserSchema);
return user;
}
where I have a file in the directory controller to make this registration
module.exports = (app) => {
return {
async cadastra(req, res) {
const User = app.models.Usuario;
const user = await User.create(req.body);
res.json(user);
}
}
only that the method of bcryptjs
indicates that the property this.password
is undefined
where I also put a console.log(this)
within the method pre
to check which returned, where it is returning empty literal object {}
Error returning in console
{}
(node:7000) UnhandledPromiseRejectionWarning: Error: Illegal arguments: undefined, number
at _async (c:\node-api\api-registro\node_modules\bcryptjs\dist\bcrypt.js:214:46)
at c:\node-api\api-registro\node_modules\bcryptjs\dist\bcrypt.js:223:17
Another detail that I forgot to say: To avoid updating all fields whenever you are going to update, avoid using the http PUT method, instead use PATCH, as it makes it possible to update each field independently, since the PUT method replaces the whole object.
– Marcos Ferreira