After adding the users to the users collection, we can retrieve all or just one of them through the routes that we created in Chapter 8, Adding a Server-Side Framework. Now we just have to refactor them using the same code structure as in the previous section for fetching real data from the database:
- Refactor the route for listing all user documents with the get method:
// server/routes.js
router.get('/users', async (ctx, next) => {
let result
//...
})
- Inside the get router, fetch all documents from the user collection by using the find API method:
result = await collectionUser.find({
}, {
// Exclude some fields
}).toArray()
If you want to exclude the fields from the query result, use the projection key and a value of 0 for the field you don't want to show in the result. For example, if you don't want the _id field on each document in the result, do this:
projection:{ _id: 0 }
- Refactor the route...