Mongooose Middleware to encrypt password in Schema

Asked

Viewed 93 times

0

I’m having a hard time putting a Middleware in my Mongoose schema. I put it as save and am getting the error that it is not a function when I call it. See below both codes:

schema.pre('save', function(next) {

console.log('this gets printed first');
console.log(user);

var user = this;

    if (!user.isModified('passwd')) return next();

    bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
        if (err) return next(err);

        bcrypt.hash(user.passwd, salt, function(err, hash) {
            if (err) return next(err);

            user.passwd = hash;
            console.log(hash);
            console.log(user.passwd);
            next();
        });
    });
});

I tried to instantiate the model in two different ways believing it would be the way I add it in the respective script

//var model = mongoose.model('User');
var model = require('../models/user');

api.add = function (req, res) {
var user = req.body;
console.log(user);
model
    .save(user)
    .then(function(user) {
        res.json(user);
    }, function(error) {
        console.log(error);
        res.status(500).json(error);
    })
}

Follow the error:

Typeerror: model.save is not a Function at api.add (/Users/admin/Androidstudioprojects/4Party/api4party/app/api/user.js:43:4)

If I put how create and even having this middleware it does not encrypt the respective password.

1 answer

0

I managed to solve, in this case it was some error with the logic I was using, simplifying it for a simple if and a salt generated with bcrypt I managed to encrypt the password field.

schema.pre('save', function(next) {
  if(this.passwd) {                                                                                                                                                        
      var salt = bcrypt.genSaltSync(10)                                                                                                                                     
      this.passwd  = bcrypt.hashSync(this.passwd, salt)                                                                                                                
  }                                                                                                                                                                          
  next()  
});

Browser other questions tagged

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