In the previous lesson we got the list of trips. Every trip has an associated _id property which is added by MongoDB directly when it’s added:

{
	"trips": [
		{
			"_id": "5bdf03aed64fb0cd04e15728",
			"name": "Yellowstone 2018"
		},
		{
			"_id": "5bdf03c212d45cdb5ccec636",
			"name": "Sweden 2017"
		},
		{
			"_id": "5bdf047ccf4f42dc368590f6",
			"name": "First trip"
		}
	]
}

We’ll use this _id to register a new expense.

If you remember, the endpoint to add a new expense is this:

POST /expense { trip, date, amount, category, description }

trip in this case will be the _id of one of the trips we previously registered. Imagine that in the app, the user will add one trip, and that will remain the current trip until a new one is added (or selected).

Let’s go ahead and implement our stub:

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

Like when adding a trip, we’re going to use the insertOne() method, this time on the expenses collection.

We get 5 parameters from the request body:

  • trip
  • date the date, in ISO 8601 format (e.g. 2018-07-22T07:22:13), in the GMT timezone
  • amount an integer with the amount
  • category which is one from travel, food, accomodation, fun
  • description a description for the expense, so we’ll remember about it later

    app.post('/expense', (req, res) => {
    expenses.insertOne(
    {
      trip: req.body.trip,
      date: req.body.date,
      amount: req.body.amount,
      category: req.body.category,
      description: req.body.description
    },
    (err, result) => {
      if (err) {
        console.error(err)
        res.status(500).json({ err: err })
        return
      }
      res.status(200).json({ ok: true })
    }
    )
    })
    

The code at this point is available at https://glitch.com/edit/#!/node-course-project-tripcost-d?path=server.js


Go to the next lesson