Mongoose pass req object for middleware

I am writing mongoose middleware that runs for each search object using pre-query.

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

      

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

Is it possible?

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

I found above, but it doesn't talk about passing a req object.

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

Edit after some confusion on the question.

What I am trying to accomplish is to get the role req.user and pass the model name to another function to get the query condition for the search. So, depending on the role of the user and the type of model available for the query condition will change.

+3


source to share


1 answer


Wrap the middleware in other middleware that has access to req

.

Something like assuming the expression

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 you want to provision.

Disclaimer - Not Verified.

0


source







All Articles