Error - Password update bcrypt

Asked

Viewed 158 times

2

I am unable to encrypt my password during an update using bcrypt in Mongoose. The password is changed smoothly but without encryption.

Follow the schema:

var mongoose= require('mongoose');
module.exports= function(){
var schema= mongoose.Schema({
    email:{
        type: String,
        required: true
    },
    senha:{
        type: String,
        required: true, 
        bcrypt: true
    },

});

schema.plugin(require('mongoose-bcrypt'));
return mongoose.model('Usuario', schema);}

Follows excerpt from the controller:

controller.updateUsuario= function(req, res){

    var Usuario= app.models.usuario;

    var _id= req.params.id;

    // Atualização de cadastro
    if(_id){
        Usuario.findByIdAndUpdate(_id, req.body).exec()
            .then(
                function(usuario){
                    res.json(usuario);
                },
                function(erro){
                    console.error(erro);
                    res.status(500).json(erro);
                }
            );
    }};

2 answers

1

I’m a beginner, but I believe the code below would help you:

controller.updateUsuario= Function(req, res){

var Usuario= app.models.usuario;
var _id = req.body._id;
var dados = {
        "nome" : req.body.nome,
        "email" : req.body.email
};

// Atualização de cadastro
if(_id){
    Usuario.findByIdAndUpdate(_id, dados).exec()
        .then(
            function(usuario){
                res.json(usuario);
            },
            function(erro){
                console.error(erro);
                res.status(500).json(erro);
            }
        );
}};

1


The problem is that the findByIdAndUpdate, and most family functions update of Mongoose, do not instantiate the Model and therefore do not execute:

  • defaults
  • setters
  • validators
  • middleware

There is a note about this at the end of the method documentation findByIdAndUpdate [1]. Recommended is to replace with:

Model.findById(id, function (err, doc) {
  if (err) ..
  doc.name = 'jason borne';
  doc.save(callback);
})

Of course, there you are making two queries and it is up to you whether this is a problem or not. I assume that when you are updating the user, you have already authenticated it and therefore already have your document in memory. In this case, you would not have to give this find, only find a way to split the instance used in the authentication with the route.

Using passport, in general, there is an instance of the document (or whatever is passed to passport.deserializeUser na propriedadereq.user`.

[1] - http://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate

Browser other questions tagged

You are not signed in. Login or sign up in order to post.