'Mongoose pass req object to middleware

I am writing a middleware for mongoose that gets executed for every find object using pre query hook.

postSchema.pre('query', function(query, next) {
// I want to access the req.user object here
    query.populate('Category');
    next();
});

I want to access req.user object inside the pre for every request made to the api server. How can i pass the object to the middleware?

Is it even possible?

https://github.com/Automattic/mongoose/issues/1931

I found the above but it doesnt talk about passing req object.

====================

Edit after some confusion about the question.

What i am trying to accomplish is to get the req.user role and the model name pass it to another function to get the query condition for find. So depending on the user role and the type of model accessed the query condition will change.



Solution 1:[1]

Wrap the middleware in another middleware that has access to req.

Something like, assuming express

router.verb('/some-route', function (req, res, next) {
   postSchema.pre('query', function(query, next) {
      console.log(req);
      query.populate('Category');
      next();
   });
});

Edit - Attach this only to the route that you want the prehook for.

Disclaimer - Not tested.

Solution 2:[2]

I know i'm joining this party late but you can use a service to pass the data you want between the request object and the mongoose prehook method. In your service create private variables that hold the data that you want to pass. Set those variables in your custom middleware and call the service get method to get the values in the mongoose prehook method.

Solution 3:[3]

Use

  1. query.op to get the type of query
  2. query.options to get other options like {runValidators: true}
  3. query._condition to get the conditions of the query
  4. query._update to get the incoming body
  5. query._fields to get the selected fields,

You can also log the query to the terminal to see various options

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 ranman
Solution 3 Ssadique Roy