1

I want to execute same script in the pre-hook with multiple methods like this:

UserSchema.pre("findOne", function(next) {
    console.log("Common code");
});

&

UserSchema.pre("findOneAndUpdate", function(next) {
    console.log("Common code");
});

So, as you can notice in the above 2 scripts that they both are executing the same code but have different methods: findOne & findOneAndUpdate.

So, is there any way to register both pre-hooks with the same code all at once?

1 Answers1

5

You can pass all the methods in the form of an array as the first argument in pre/post hook methods, like this:

UserSchema.pre(["findOne", "findOneAndUpdate"], function(next) {  // ["method1", "method2", "method3"...]
    console.log("Common code");
});

And now you can register & execute the same script for multiple methods.