[question] Accessing 'req' object in a mongoose middleware
See original GitHub issueCan I somehow add req.user._id
to document before saving it.
Something like:
schema.pre('save', function (next) {
this.createdBy = req.user._id; // is it possible to access req here?
next()
})
Do you know if it is possible to achieve something like that?
Issue Analytics
- State:
- Created 7 years ago
- Comments:5
Top Results From Across the Web
Mongoose pass req object to middleware - Stack Overflow
What i am trying to accomplish is to get the req.user role and the model name pass it to another function to get...
Read more >Mongoose v6.8.2: Middleware
Query middleware is supported for the following Query functions. Query middleware executes when you call exec() or then() on a Query object, or...
Read more >Middleware in Express.js - GeeksforGeeks
Middleware has the access to the request object, responses object, and next, it can process the request before the server send a response....
Read more >Express/Node introduction - Learn web development | MDN
The middleware can perform any operation, execute any code, make changes to the request and response object, and it can also end the...
Read more >How To Use the req Object in Express - DigitalOcean
Express servers receive data from the client side through the req object in three instances: the req.params , req.query , and req.body objects....
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
My highly opiniated view on this is that you should not use
req
in your models as it couples your database with your web framework so I would recommend using the method I outlined above.That said, we could investigate passing
req
into save. However, I’m curious as to what happens in the case of async middleware.Mongoose middleware doesn’t have access to the request object, it is also a separate project for which you can find documentation in their repository.
What you can do, is use our preCreate middleware.