Mongooose Middleware to encrypt password in Schema

0

I'm having a hard time getting a Middleware in my schema with mongoose. I put it as save and I'm 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 its 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);
    })
}

The following is 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 to create and even having this middleware it does not encrypt the respective password.

    
asked by anonymous 24.08.2017 / 19:53

1 answer

0

I was able to resolve, in this case it was some error with the logic I was using, simplifying it to a simple if and a salt generated with bcrypt I was able 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()  
});
    
24.08.2017 / 20:16