i am first time using pre save middleware and getting a bit confusion in it.
It runs perfectly fine and also my save method is getting executed eventhough i am not calling the next()
case 1
tourSchema.pre('save', function () {
console.log('first middleware is getting called');
})
But when i do like this when next is declared inside the function params but i don't call the next() it hangs there and the save method is not getting executed
case 2
tourSchema.pre('save', function (next) {
console.log('first middleware is getting called');
});
But as soon as i call the next() it gets executed
case 3
tourSchema.pre('save', function (next) {
console.log('first middleware is getting called');
next()
});
so i only want to know what's the wrong with the second case . In this i have only and only this pre middleware . How defining the next inside the function params can matter, the save method should also be executed in the second case since i don't have any second pre middleware.
mongoose uses kareem library to manage hooks.
kareemsmakes use of thelengthproperty of your hook function to determine whethernextis defined as an argument or not.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length
Your first function has no arguments,
kareemwill assume this is a sync functionYour second function has 1 argument, the
kareemlibrary will see your function acceptnextarguments. It will pass a callback and execute it in thenextfunction. Sincenextis never called, that callback will be never called.