To retrieve the full list of teams, we will make use of the GET HTTP method. Let's start by cleaning up our code a little bit. Until now, we have been using an array of teams; we won't need it anymore, so let's remove it. In src/routes/teams-api.js, apply the following changes:
...
api
.route('/teams')
.get((req, res) => {
// TODO
})
.post((req, res, next) => {
let team = new Team(req.body)
team.save()
.then(data => res.json(data))
.catch(err => next(err) )
})
api
.route('/teams/:id')
.get((req, res) => {
// TODO
})
.put((req, res) => {
// TODO
})
.delete((req, res) => {
// TODO
})
...
Now that we have our code cleaned, add the following change to implement the logic to retrieve the full list of teams:
...
api
.route('/teams')
.get((req, res, next) => {
Team.find()
.then(data => res.json(data))
.catch(err => { next(err) })
})
.post((req, res, next) => {
let team = new Team(req.body)
team.save()
.then(data => res.json(data))
.catch(err => { next(err) } )
})
...
First, we call the find method to return a Promise as the save function used to create new teams. As it is a Promise, we will receive the data returned from the database into the then function and if something goes wrong, it will return an error in the catch function. Let's test it:
$ curl http://localhost:3000/teams
[{"_id":"5a662fbf728726072c6298fc","name":"Peru","ranking":11,"captain":"Paolo Guerreo","Trainer":"Ricardo Gareca","confederation":"CONMEBOL","__v":0}]
Awesome! Now we are able to retrieve the list of teams using the api we just implemented. Let's continue!