Loading

Whenever the Express app receives a request to a route that matches a path containing the :userId param in it, the app will first execute the userByID controller function before propagating to the next function 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 param to query the database by _id, and load the matching user's details.

mern-skeleton/server/controllers/user.controller.js:

const userByID = (req, res, next, id) => {  User.findById(id).exec((err, user) => {    if (err || !user)      return res.status('400').json({        error: "User not found"      })    req.profile = user    next()  })}

If a matching user is found ...

Get Full-Stack React Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.