So far, you have only one index route: Hello World. Create more routes so that you can retrieve all the movies from the database and save them.
Set up the middleware before all the routes, as follows:
app.use(require('./middleware/db').connectDisconnect);
Recall that you ran the create
command on the index.js
file earlier. Now perform these tasks:
- Bundle two files (
index
anddb
). - Specify the secrets (
env
). - Watch for the changes.
Run this command line for them all:
wt create index --secret MONGO_URL=<MONGOLAB-CONNECTION-URL> --bundle --watch
Grab the URL from the database home:
Add the following route immediately after the /
route:
app.post('/movies', (req, res) => {
const newMovie = new req.movieModal(
Object.assign(req.body, { created_at: Date.now() })
);
newMovie.save((err, savedMovie) => {
res.json(savedMovie);
});
});
The above code does the following:
- Create a new movie with the movie modal.
- Save that movie and return the saved version to the client.
Finally, test with Postman:
Add this route to retrieve all the existing movies:
app.get('/movies', (req, res) => {
req.movieModal
.find({})
.sort({ created_at: -1 })
.exec((err, movies) => res.json(movies));
});
Subsequently, that route finds the movies, sorts them by date in reverse order, and returns them: