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?

asked Apr 26, 2021 at 13:55

1 Answer 1

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.

answered Apr 26, 2021 at 13:55
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.