Use app.param to convert route parameters into objects
https://expressjs.com/en/api.html#app.param
api.param('collection', function (req, res, next, id) {
Collection.find(id).then(collection => {
req.collection = collection
next()
}).catch(next)
})
For a route like /collections/:collection
, this will look up the collection in the database and set it on the request object before the route's handler is called. This avoids having to do Collection.find(id)
in the route handler, and - importantly - means that the collection object is available to authorisation middleware.
It may be preferable to use :collection_id
rather than :collection
as the parameter name.