Updating the userByID controller method

When a single user is retrieved from the backend, we want the user object to include the names and IDs of the users referenced in the following and followers arrays. To retrieve these details, we need to update the userByID controller method to populate the returned user object.

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

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

We use the Mongoose populate method to specify that the user object returned from the query should contain the name ...

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.