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 in the database, the user object is appended to the request object in the profile key. Then, the next() middleware is used to propagate control to the next relevant controller function. For example, if the original request was to read a user profile, the next() call in userById would go to the read controller function.