Before we start, we should look at the code structure that we need for every route that we will be creating:
// server/routes.js
router.get('/user', async (ctx, next) => {
let result
try {
const connection = await mongo.connect()
const collectionUsers = connection.collection('users')
result = await collectionUsers...
mongo.close()
} catch (err) {
ctx.throw(500, err)
}
ctx.type = 'json'
ctx.body = result
})
Let's discuss the structure:
- Catching and throwing errors:
When we use the async/await statement instead of the Promise object for an asynchronous operation, we must always wrap them in try/catch blocks to handle errors:
try {
// async/await code
} catch (err) {
// handle error
}
- Connecting to MongoDB databases and collections:
Before performing any CRUD operation, we must establish the connection and connect to the specific collection that we want to manipulate. In our case, the...