Error - Password update bcrypt mongoose without encryption

2

I am not able to encrypt my password during an update using bcrypt on mongoose. The password is changed without problems, 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);}

The following is an 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);
                }
            );
    }};
    
asked by anonymous 28.05.2015 / 14:50

2 answers

1

The problem is that findByIdAndUpdate , as well as most functions in the update family, do not instantiate Model and therefore do not execute:

  • defaults
  • setters
  • validators
  • middleware

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

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

Of course, there you are doing two queries and it is up to you whether this is a problem or not. I suppose 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 , just figure out how to split the instance used in authentication with the route.

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

[1] - link

    
01.09.2015 / 00:33
1

I'm a beginner, but I think the code below would help:

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);
            }
        );
}};
    
21.06.2016 / 05:37