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?
I found the above but it doesnt talk about passing req object.
====================
Edit after some confusion about the question.
What i am trying to acplish 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.
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./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 acplish 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.
Share Improve this question edited Nov 23, 2016 at 9:37 Josip Ivic 3,7099 gold badges41 silver badges58 bronze badges asked Jul 10, 2015 at 1:37 Uma MaheshwaraaUma Maheshwaraa 6032 gold badges10 silver badges18 bronze badges 04 Answers
Reset to default 0Wrap 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.
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.
Use
query.op
to get the type of queryquery.options
to get other options like{runValidators: true}
query._condition
to get the conditions of the queryquery._update
to get the ining bodyquery._fields
to get the selected fields,
You can also log the query to the terminal to see various options
Yes, it is possible.
restify.serve(router, model, {
preCreate: function (req, res, next) {
req.body.createdBy = req.user._id
next()
}
})
Follow this doc