Deleting a contact

The destroy route will take an id route parameter and delete the contact with that id from the database, using the mongoose .findByAndDelete() method:

// ./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
};
},

async destroy(ctx) {
const { id } = ctx.params;
await Contact.findByIdAndDelete(id);
ctx.body = {
status: 'success',
message: 'contact successfully deleted'
};
}
};

We add the corresponding router definition, 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)
.delete('/contact/:id', contactController.destroy);

// ...

Making a request to DELETE /contact/{contactId} with the specified id should return a response similar to the following:

{
"status": "success",
"message": "contact successfully deleted"
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.143.181