We offer the client a way to add trip using the POST /trip endpoint:

app.post('/trip', (req, res) => { /* */ })

Let’s go ahead and implement it.

We already included the MongoDB library, so we can use it in our endpoint implementation.

const mongo = require('mongodb').MongoClient

Next, we build the MongoDB server URL. If you are running the project locally, and MongoDB locally too, the URL is likely this:

const url = 'mongodb://localhost:27017'

because 27017 is the default port.

Next, let’s connect to the database using connect():

let db

mongo.connect(
  url,
  (err, client) => {
    if (err) {
      console.error(err)
      return
    }
    db = client.db('tripcost')
  }
)

and while we’re here, let’s also get a reference to the trips and expenses collections:

let db, trips, expenses

mongo.connect(
  url,
  (err, client) => {
    if (err) {
      console.error(err)
      return
    }
    db = client.db('tripcost')
    trips = db.collection('trips')
    expenses = db.collection('expenses')
  }
)

Now we can go back to our endpoint.

This endpoint expects 1 parameter, name, which represents how we call our trip. For example Sweden 2018 or Yosemite August 2018.

See my tutorial on how to retrieve the POST query parameters using Express

We expect data coming as JSON, using the Content-Type: application/json, so we need to use the express.json() middleware:

app.use(express.json())

We can now access the data by referencing it from Request.body:

app.post('/trip', (req, res) => {
  const name = req.body.name
})

Once we have the name, we can use the trips.insertOne() method to add the trip to the database:

app.post('/trip', (req, res) => {
  const name = req.body.name
  trips.insertOne({ name: name }, (err, result) => {
  })
})

If you get an error like “could not read property insertOne of undefined”, make sure trips is successfully set in mongo.connect(). Add a console.log(trips) before calling insertOne() to make sure it contains the collection object.

We handle the error, if present in the err variable, otherwise we send a 200 response (successful) to the client, adding an ok: true message in the JSON response:

app.post('/trip', (req, res) => {
  const name = req.body.name
  trips.insertOne({ name: name }, (err, result) => {
    if (err) {
      console.error(err)
      res.status(500).json({ err: err })
      return
    }
    console.log(result)
    res.status(200).json({ ok: true })
  })
})

That’s it!

Now restart the Node application by hitting ctrl-C to stop it, and run it again.

You can test this endpoint using the Insomnia application, a great way to test and interact with REST endpoints:

Project up to now https://glitch.com/edit/#!/node-course-project-tripcost-b?path=server.js


Go to the next lesson