Creating Matches

Creating a new Match is simple. We just need to import the Match model and call its built-in save method, as follows:

const express = require('express')
const api = express.Router()
const Match = require('../models/match')

api
.route('/admin/match/:id?')
.post((req, res, next) => {
const match = new Match(req.body)
match.save()
.then(data => res.json(data))
.catch(err => next(err) )
})
.put((req, res, next) => {

// logic to update Match

})


module.exports = api

First, we import the Match model. Then, in the POST method, we create a new Match object and call the save function. If the operation is successful, we send the new Match via the res.json method. To test our creation logic, we need to configure the server.js to use our new Admin API, as follows:

const express = require('express')
...
const adminApi = require('./src/routes/admin-api')
const mongooseConfig = require('./src/config/mongoose-connection')
const app = express()

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

app.use((err, req, res, next) => {

Once we have applied the previous change, open a new terminal to test things out:

$ curl -X POST -H "Content-type: application/json" -d '{"team_1": "Peru", "team_2": "Chile", "score": { "team_1": 20, "team_2": 0} }'  localhost:3000/admin/match/

{"__v":0,"team_1":"Peru","team_2":"Chile","_id":"5a94a2b8221bb505c92d801c","score":{"team_1":20,"team_2":0}}

Cool! Now we have our creation logic up and running with a great real example.

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

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