Lastly, we also will be using the same code structure as in the previous section to delete existing users from the users collection in the following steps:
- Create a route with the del method to delete an existing user document:
// server/routes.js
router.del('/user', async (ctx, next) => {
let result
//...
})
- Before deleting the document with the deleteOne API method, inside the del route, as always, we use the findOne API method to find this document to make sure we have it in the user collection first:
let body = ctx.request.body || {}
const found = await collectionUser.findOne({
_id: mongo.objectId(body.id)
})
if (!found) {
ctx.throw(404, 'no user found')
}
result = await collectionUser.deleteOne({
_id: mongo.objectId(body.id)
})
Well done! You have managed to get through writing MongoDB CRUD operations and integrating them into the API (Koa). The final part of this chapter involves ...