Creating a new team

To create a new team, we need to call the model's built-in methods provided by Mongoose. The save function is used to create and update the fields for any model. So, first we will start importing the Team model into the src/routes/teams-api.js file, as follows:

const express = require('express')
const api = express.Router()
const Team = require('../models/team')

let teams = [
{ id: 1, name: "Peru"},
{ id: 2, name: "Russia"}
]
...

Now that we have imported the module with the require function and stored it into the Team constant, we can use it to create a new team. Let's modify the POST HTTP method of the Rest Controller:

...
api
.route('/teams')
.get((req, res) => {
res.json(teams)
})
.post((req, res, next) => {
let team = new Team(req.body)

team.save()
.then(data => res.json(data))
.catch(err => next(err) )
})
...

The first change to note is the next param into the function. This param is used to throw an error to express in case Mongoose is not able to create a new team. Then, we create a new team, passing the body param from the req object and calling the save function. The save function returns a Promise that is just an asynchronous call, which, when finished successfully, will return the information of the new team saved into the then method. Once we have the data, we send the information as a JSON type to the client.

Let's test things out. First, we need to get the server up by executing node server.js and then we will use cURL to test this endpoint. Open your Terminal and run the following command:

$ curl -X POST -H 'Content-type: application/json' -d '{"code": "GER", "name": "Germany", "ranking": 8, "captain": "Paolo Guerreo", "Trainer": "Ricardo Gareca", "confederation": "Conmebol"}' http://localhost:3000/teams

{"__v":0,"name":"Germany","ranking":8,"captain":"Paolo Guerreo","Trainer":"Ricardo Gareca","confederation":"CONMEBOL","_id":"5a662fbf728726072c6298fc"}

If everything went right, you should see the JSON object responding with the autogenerated _id attribute. Let's see what happens if we run it again:

$ curl -X POST -H 'Content-type: application/json' -d '{"code": "PER", "name": "Peru", "ranking": 11, "captain": "Paolo Guerreo", "Trainer": "Ricardo Gareca", "confederation": "Conmebol"}' 

http://localhost:3000/teams

MongoError: E11000 duplicate key error collection: wcDb.teams index: name_1 dup key: { :"Peru" }
...

Now we receive an ugly error that says we are falling in a duplication key error. Why is this happening? Let's get answers from the model schema that we defined earlier. Open the src/models/team.js file:

const mongoose = require('mongoose')

const TeamSchema = new mongoose.Schema({
name: {
type: String,
min: 3,
max: 100,
required: true,
unique: true
},

...

Hot dog! You have the answer. The error we are facing, is because we defined the name property as unique:true.

We will need to fix something in the message. We expect a JSON response from the REST API, so let's configure a global exception handler in our backend to send the error as a JSON object instead of an ugly and incomprehensible HTML page. Open the server.js file and apply the following change:

const express = require('express')
const bodyParser = require('body-parser')
const teamsApi = require('./src/routes/teams-api')
const mongooseConfig = require('./src/config/mongoose-connection')
const app = express()

app.use(bodyParser.json())
app.use(teamsApi)

app.use((err, req, res, next) => {
return res.status(500).send({ message: err.message })
})


app.listen(3000, () => {
console.log('running on port: 3000')
})

We defined a global middleware, which is a function that expects four params:

  • err: Contains null if no error is thrown; otherwise, it's an instance of error or another value
  • req: The source request sent by the client
  • res: The response property
  • next: The reference to the next action that Express.js will call

As is expected, all the errors return an HTTP status different than 200. Until we define the correct status of the other CRUD operations, let's leave it with status(500) by default. Now, let's run it again and see what happens:

$ curl -X POST -H 'Content-type: application/json' -d '{"code": "PER", "name": "Peru", "ranking": 11, "captain": "Paolo Guerreo", "Trainer": "Ricardo Gareca", "confederation": "Conmebol"}' http://localhost:3000/teams

{"error":"E11000 duplicate key error collection: wcDb.teams index: name_1 dup key: { : "Peru" }"}

As you can see, we receive a JSON object with a single error attribute. Cool! Let's continue and learn how to retrieve the full list of teams.

..................Content has been hidden....................

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