Updating

The API endpoint to update a single user is declared in the following route.

mern-skeleton/server/routes/user.routes.js:

router.route('/api/users/:userId').put(userCtrl.update)

When the Express app gets a PUT request at '/api/users/:userId', similar to the read, it first loads the user with the :userId param value, and then the update controller function is executed.

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

const update = (req, res, next) => {
let user = req.profile
user = _.extend(user, req.body)
user.updated = Date.now()
user.save((err) => {
if (err) {
return res.status(400).json({
error: errorHandler.getErrorMessage(err)
})
}
user.hashed_password = undefined
user.salt = undefined
res.json(user)
})
}

The update function retrieves the user details from req.profile, then uses the lodash module to extend and merge the changes that came in the request body to update the user data. Before saving this updated user to the database, the updated field is populated with the current date to reflect the last updated at timestamp. On successful save of this update, the updated user object is cleaned by removing the sensitive data, such as hashed_password and salt, before sending the user object in the response to the requesting client.