April 2020
Intermediate to advanced
716 pages
18h 55m
English
Whenever the Express app receives a request to a route that matches a path containing the :userId parameter in it, the app will execute the userByID controller function, which fetches and loads the user into the Express request object, before propagating it to the next function that's specific to the request that came in.
mern-skeleton/server/routes/user.routes.js:
router.param('userId', userCtrl.userByID)
The userByID controller function uses the value in the :userId parameter to query the database by _id and load the matching user's details.
mern-skeleton/server/controllers/user.controller.js:
const userByID = async (req, res, next, id) => { try { let user = await User.findById(id) if (!user) return res.status('400').json({ error: ...