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.