Create a movie reviews app with Node.js and Express
Part 7 - Add data to the database
Build web apps with NodeJS & Express
🕑 This lesson will take about 20 minutes
In this lesson, you will learn how to retrieve data that has been entered into a form by a user and then add that data to a MongoDB database. We will take the user input from the form on the “add movie” page and add the movie details to the database. In the previous lesson, we added the form to the ‘add.ejs’ template file. In this lesson, we will add the server-side code (in the index.js file) to handle a POST request for the ‘/add’ route.
First, add the following code near the top of your index.js file so your app is ready to handle data from the form sent to the server in the POST request:
app.use(express.urlencoded({
extended: true
}));
Next, you will need to add the route to handle the POST. Add the following code below the app.get(‘/add’) function but make sure it is above the app.listen() function (scroll down for the full code for the index.js file).
// Add movie data to the database
app.post('/add', (req, res) => {
var data = req.body;
console.log(data);
Movie.create({
title: data.title,
director: data.director,
genre: data.genre,
releaseYear: data.releaseYear,
rating: data.rating,
review: data.review,
thumbnailImage: data.thumbnailImage
})
.then((result) => {
console.log("Movie data added to the database");
// Redirect user to the home page
res.redirect('/');
})
.catch((err) => {
console.log("Movie data could not be added to database.");
res.render('add', {});
})
});
Restart the server and click the “+ Add new movie” button on the home page to navigate to the “add movie” page. Add some movie data to the form and then submit the form. You should be redirected back to the home page and should see the new movie details on that page.
Here is the full code for the index.js file: