Read: Class 09 API Server - 401-advanced-javascript-muna/amman-javascript-401d1 GitHub Wiki

API Server

Express: Router Parameters

  • parameters in routes can be read ex:

app.get('/places/:city', (req,res) => {

// req.params.city is now a readable value

})

  • We can run middleware on any route

app.get('/places/:city', getZip, (req,res) => {

// req.params.city is read from the param

// req.body.zip was grafted onto the request object by the getZip middleware

})

  • We can also run middleware on every request

ex 👍 app.use(getZip)

Those are both pretty extreme. Middleware that has to run on 10 out of 15 of your routes (e.g. any route with a city) requires you to either put it on all the routes and make it ignore the requests without a city (ugly) or put that special middleware on every route with a city parameter (also ugly).

  • Express lets you run middleware only when certain parameters are present and expected, eliminating that choice.

router.param('city', function (req, res, next, id) {

console.log('Only runs on routes that have a city param')

next()

})

// That middleware will not run here

router.get('/places/seattle', function (req, res, next) {

res.send(Zip: ${req.body.zip});

})

// That middleware does run here

router.get('/places/:city', function (req, res, next) {

res.send(Zip: ${req.body.zip});

})

// But not here

router.get('/flights/to/:airport', function (req, res, next) {

res.send(Zip: ${req.body.zip});

})

Sub Documents in Mongoose

  1. Mongoose is a schema driven ORM, which gives us the opportunity to provide structure to our Mongo documents. By default, Mongo (all NoSQL Databases, really) are not structured by default. Mongoose takes some of that pain away from us as developers and allows us to provide some level of rules and validation around our data models.

  2. Mongoose gives you the ability to take that a step further and use a schema to describe a deeper part of a data model. This can be useful when a document contains potentially a list of other documents. For example, an online store likely has a collection of products. They probably also have a list of customers, each of which has placed orders which contain one or more products. When modeling the users collection, it would be nice to add orders as an array, and within the orders, and array of items … if you’ve previously modeled an item, you can re-use that schema within the orders section of a customer to keep the shape of that data the same.

Note: Simply sharing a schema as a sub-document doesn’t bring in or connect the data, it simply uses the schema/rules. It’ll be up to you to manage the actual data