ShaSha:
este es mi modelo de usuario:
const schema = new mongoose.Schema({
name: {
type: String,
required: true,
min: 6,
max: 255
},
email: {
type: String,
required: true,
min: 6,
max: 255
},
password: {
type: String,
required: true,
max: 1024,
min: 6
}
});
schema.pre("save", async next => {
if (!this.isModified("password")) return next();
try {
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
return next();
} catch (error) {
return next(erro);
}
});
module.exports = mongoose.model("User", schema);
Cuando guardo usuario, devuélvalo objeto vacío y no se guarda y no funciona. No sé lo que debe hacer? ¿Cuál es el problema?
SuleymanSah:
Debe usar el formulario función en lugar de la función de flecha dentro de la pre Guardar middleware. Dado que las funciones de flecha no se unen a su propio presente.
schema.pre("save", async function(next) {
if (!this.isModified("password")) return next();
try {
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
return next();
} catch (error) {
return next(error);
}
});