Reputation: 4122
pre('save')
or pre('validate')
does not trigger when I save the data. Although, it is saving the data without triggering the pre function. Not sure what I am doing wrong.
var userSchema = new Schema({...});
var User = module.exports = mongoose.model('User', userSchema);
userSchema.pre('save', function(next){ // tried with pre('validate')
console.log('triggered...');
next();
});
// adding a user
module.exports.addUser = function(user, callback){
var newUser = new User(user);
newUser.save(callback);
//or
User.create(user, callback);
}
Upvotes: 1
Views: 1119
Reputation: 203329
Hooks only work if you define them before creating the model:
var userSchema = new Schema({...});
userSchema.pre('save', function(next){ // tried with pre('validate')
console.log('triggered...');
next();
});
var User = module.exports = mongoose.model('User', userSchema);
Upvotes: 2