The show route will retrieve a single contact from the database, via a specified id, and send it back as a response to the client. We can get the required id from the route parameter, and easily pass it to the mongoose .findById() method, in order to retrieve the required contact. We update the controller, as follows:
// ./controllers/ContactController.js
// ...
module.exports = {
// ...
async show(ctx) {
const { id } = ctx.params;
const contact = await Contact.findById(id);
ctx.body = {
status: 'success',
data: contact
};
}
};
We then add the corresponding route, 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);
// ...
Making a request to retrieve a contact that we have already saved by calling GET /contact/{contactId} should return a response similar to the following:
{
"status": "success",
"data": {
"_id": "5be8e3028053210ddc1d162b",
"name": "Test name",
"address": "Street 5",
"company": "test company",
"createdAt": "2018-11-12T02:18:42.377Z",
"updatedAt": "2018-11-12T02:18:42.377Z",
"__v": 0
}
}