I would like to validate params using these kind of middleware. The problem is that router.param is always applied before the first middleware router.all (I also tried with router.use, it doesn't work because the param is common to both middlewares). Is there a way to execute Middleware 1 before router.param ?
// Middleware 1
router.all('/:firstId/checklist/:**secondId**/*',
(req, res, next) => {
console.log('Request matched')
next()
},
param('**secondId**', "Error message 2")
.isMongoId(),
checkValidationErrors
)
router.param('**secondId**', callback)
However, Middleware 1 does not work as I expected. If the param is a valid MongoDB ObjectId, 'Request matched'
is logged, the next middlewares are applied accordingly depending on the request. If it is not a valid id, 'Request matched'
is NOT logged, the expected error is NOT sent in the response. I get this error instead from Mongoose which comes from router.param :
MongooseError [CastError]: Cast to ObjectId failed for value "xxx" at path "_id" for model "XXX"
I tried to comment router.param and it solved the problem. So it is certainly related to the order of execution.
Thank you very much for your help