express

How to send a response when not having access to the res object in express?


I am in a place in my code where I don't have access to (req, res, next) of express, so express will not reach my code to invoke my function.

the place where I am is in mongoose pre('save') middleware, I am hashing the user password there, but I don't have access to res in case the hashing failed. so I will not be able to send a response to the client in case of a failure, is there any way to call the res object outside express handlers or middlewares? outside the stack somehow? like for instance, exporting the res from express then sending a JSON response with status code of 500?


Solution

  • My approach will be throwing an error inside the mongoose middleware, in this case, mongoose pre('save') middleware. And, write an express error-handling middleware to catch any errors. In the error-handling middleware, you can send a response to the client.