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.