Full-Stack Web Development with Vue.js and Node

(singke) #1
Introducing REST APIs Chapter 4

Adding a PUT endpoint in the users controller

Let's update a user with ID 5a3153d7ba3a827ecb241779 (change this ID to the ID of your


document), which we just created. Let's rename the email: to do that, first let's add the


endpoint in our users controller, in other words, controllers/user.js:


// update a user
app.put('/users/:id', (req, res) => {
User.findById(req.params.id, 'name email', function (error, user) {
if (error) { console.error(error); }

user.name = req.body.name
user.email = req.body.email
user.save(function (error, user) {
if (error) { console.log(error); }
res.send(user)
})
})
})

What we did here is, we added an endpoint for a PUT request, which takes the name and


email as parameters and saves it to the database. The corresponding Postman would look
as follows:

Free download pdf