Deleting

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

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

router.route('/api/users/:userId').delete(userCtrl.remove)

When the Express app gets a DELETE request at '/api/users/:userId', similar to the read and update, it first loads the user by ID, and then the remove controller function is executed.

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

const remove = (req, res, next) => {
let user = req.profile
user.remove((err, deletedUser) => {
if (err) {
return res.status(400).json({
error: errorHandler.getErrorMessage(err)
})
}
deletedUser.hashed_password = undefined
deletedUser.salt = undefined
res.json(deletedUser)
})
}

The remove function retrieves the user from req.profile and uses the remove() query to delete the user from the database. On successful deletion, the requesting client is returned the deleted user object in the response.

With the implementation of the API endpoints so far, any client can perform CRUD operations on the user model, but we want to restrict access to some of these operations with authentication and authorization.