Full-Stack Web Development with Vue.js and Node

(singke) #1
Introducing REST APIs Chapter 4

Here, we can see that the user's name has been updated. And, if we look at the request
parameters, we have also added an age parameter. But since we haven't added age to our


Schema while defining the User model, it discards the age value but updates the rest.


We can also use the PATCH method to update a resource. The difference
between the PUT and PATCH methods is: the PUT method updates the
whole resource, whereas PATCH is used for a partial update on resources.

Adding a DELETE endpoint in the users controller

Similarly, for delete, let's add an endpoint in controllers/users.js:


// delete a user
app.delete('/users/:id', (req, res) => {
User.remove({
_id: req.params.id
}, function(error, user){
if (error) { console.error(error); }
res.send({ success: true })
})
})

The preceding code takes the ID of the user and removes the user with the given ID from


the database. In Postman, the endpoint would look as follows:

Free download pdf