sinusGob sinusGob - 4 months ago 13
Node.js Question

How do i pass an mongoose id to a middleware?

My goal is to pass a mongoose id to an express middleware, but seems like It is not possible from my perspective, I tried to pass in req.params.id, but it returns an error

var middleware = require('./middleware');

app.get('/hello/:id', middleware.testing(req.params.id), function(req, res) {
// do something

})


Middleware

exports.testing = function(id) {
// do something

}

str str
Answer

You are using the middleware in a wrong way. A middleware already has access to req.params. What you do is actually calling the middleware instead of passing it as a callback.

Use this code instead:

var middleware = require('./middleware');

app.get('/hello/:id', middleware.testing, function(req, res) {
    // do something
});

Middleware

exports.testing = function(req, res) {
    // do something with req.params.id
}
Comments