The update route will update an existing contact with new details. We can achieve this by getting the required id as a route parameter, along with the updated content from the request body, then using the mongoose .findByIdAndUpdate() method to update the specified contact. The route will return the updated contact as a response on a successful update:
// ./controllers/ContactController.js
// ...
module.exports = {
async index(ctx) {
const contacts = await Contact.find();
ctx.body = {
status: 'success',
data: contacts
};
},
async store(ctx) {
const { body } = ctx.request;
let contact = new Contact(body);
contact = await contact.save();
ctx.body = {
status: 'success',
data: contact
};
},
async show(ctx) {
const { id } = ctx.params;
const contact = await Contact.findById(id);
ctx.body = {
status: 'success',
data: contact
};
},
async update(ctx) {
const { id } = ctx.params;
const { body } = ctx.request;
await Contact.findByIdAndUpdate(id, body);
const contact = await Contact.findById(id);
ctx.body = {
status: 'success',
message: 'contact successfully updated',
data: contact
};
}
};
The corresponding router definition is shown as follows:
// ./middleware/router.js
// ...
router
.get('/', async ctx => (ctx.body = 'Welcome to the contacts API!'))
.get('/contact', contactController.index)
.post('/contact', contactController.store)
.get('/contact/:id', contactController.show)
.put('/contact/:id', contactController.update);
// ...
An example request to PUT /contact/{contactId} to update a contact is shown in the following screenshot: