Latest Data on the Homepage
The Home Page
Currently our application does not have a homepage. We would like a home page that includes the three latest films.
This will require a view, route and controller.
The Index View
There is a view provided with the repo at views/index.ejs
.
Review the view and see how it makes use of partials as well as loops and links covered in the example pages from previously.
Add a Controller
We need to query our model to extract the latest three films. We have a releaseDate
field to help us here. Add a controller of:
Inside the try block, the Film.find()
method is called to retrieve films from the MongoDB collection. The Film here refers to a MongoDB model or schema that represents the films collection.
The find()
method without any parameters retrieves all documents from the films collection. Following that, the sort()
method is used to sort the films based on the releaseDate
field in descending order (-1 indicates descending order).
The limit()
method is then applied to the query to limit the result to the latest three films.
The await
keyword is used before the Film.find().sort().limit() chain to wait for the database query to complete and fetch the results. The results are assigned to the newestFilms
variable.
Note: Don't forget to add getNewestFilms
to the exported functions.
Add a Route
We now have a homepage that features the three latest film releases.
Next: Getting Started