Create a movie reviews app with Node.js and Express

Part 3 - Create a schema and add data to the database

Build web apps with NodeJS & Express

🕑 This lesson will take about 30 minutes

In this lesson, we will create a schema and add some data to the database. A schema is like a blueprint that defines the types of data that will be stored in the database eg. movie title, director’s name, year of release, etc. A database schema defines the structure of the database, how the data is organised, and the type of data stored.

Step 1 - Create a schema and model

Add the following code to create a schema for movies in the database. A database model is then used to specify the schema that will be used to add movies to the movies collection in the database. Each new movie that is added to the database will be a 'document' in the movies 'collection', all stored inside the movie database.

This code should be placed below the mongoose.connect() function and above the app.listen() line of code.

// Create a database schema for movies
var movieSchema = new mongoose.Schema({
title: String,
director: String,
genre: String,
releaseYear: Number,
rating: Number,
review: String,
thumbnailImage: String
});

// Create a model for movies
var Movie = mongoose.model("Movie", movieSchema);

Step 2 - Add some test data to the database

Now that we have a schema and a model, we are ready to start adding movies to the database. To test this out, add the following code beneath the code you just added to the index.js file (you can change the movie information if you like):

// Create a movie
Movie.create({
title: "Star Wars: The Force Awakens",
director: "JJ Abrams",
genre: "SciFi",
releaseYear: 2015,
rating: 4,
review: "It was pretty good",
thumbnailImage: "https://upload.wikimedia.org/wikipedia/en/a/a2/Star_Wars_The_Force_Awakens_Theatrical_Poster.jpg"
})
.then((result) => {
console.log("Data successfully added to collection.");
})
.catch((err) => {
console.log("Error: Data could not be added to collection.");
})

Here is the complete code for the index.js file so far:

Now run the server (use the command node index.js in your terminal, or click Run if using replit.com). If all goes well, you should see the following messages displayed in the terminal confirming that the server has started, the app is connected to the database, and data has been successfully added to the database:

Server started
MongoDB Connected
Data successfully added to collection.

If you receive an error message instead, check your code to ensure the schema and model are set up correctly and that the data specified in the Movie.Create() function is formatted properly.

Now go back to MongoDB Atlas, and click on “Browse Collections” from the Database page.

Select the movies collection and you should see a new document containing all the data you just added to the database.

Step 3 - Retrieve all movie data from the database

Now that we know that we can successfully add data to the database, we can remove the Movie.create() function from the index.js file. Remove the Movie.create() block from your code (if you keep this block of code here, the same movie data will be added to your database every time you restart the server). We will use this code again later and modify it so that we can collect information about movies from users through a form and then add the movie information to the database.

Replace the Movie.create() block of code with the following block of code. The Movie.find() function will fetch all movies from the database, and in this example, display the results in the terminal.

// Retrieve all movies from the database
Movie.find({})
.then((result) => {
console.log("Data successfully retrieved from the database:");
console.log(result);
})
.catch((err) => {
console.log("Error: There was a problem getting data from the database.");
})

Start the server again and you should see the data retrieved from the database displayed in the terminal.

Step 4 - Retrieve specific data from the database

Modify the Movie.find() function by specifying search criteria between the { and } brackets. In the example below, we are searching all movies that match the genre “SciFi”.

// Retrieve SciFi movies from the database
Movie.find({
genre: "SciFi"
})
.then((result) => {
console.log("Data successfully retrieved from the database:");
console.log(result);
})
.catch((err) => {
console.log("Error: There was a problem getting data from the database.");
})

Start the server again and you should retrieve only SciFi movies from the database.

You can also add more criteria by adding a comma between each criterion. In the example below, we are searching for all action movies from 2023.

// Retrieve 2023 action movies from the database
Movie.find({
genre: "Action",
releaseYear: "2023,
})
.then((result) => {
console.log("Data successfully retrieved from the database:");
console.log(result);
})
.catch((err) => {
console.log("Error: There was a problem getting data from the database.");
})

Tip: You can use the findOne() function to retrieve just one record (the first record) that matches your criteria. To do this, replace find with findOne. The findOne() function is useful when you want to retrieve data that there would be only one instance of eg. a specific user’s profile.

Now that you know that the app can retrieve data from the database, you can now remove the Movie.find() function from the index.js file. We’ll use this function in the next lesson but inside the app.get(‘/’) function so that movies can be displayed on the home page.

Here is the full sample code:

We are now ready to start building the app so that we can view and add movies. In the next lesson, we will create the home screen for the app that will display a list of movies from the database.

Next lesson: Create a Movie Reviews app (Part 4 - Create the home page)