In this workbook, you will learn how to create a Node.js application with a MongoDB server to model a student enrollment database and an Express.js server to interact with the database. We will also include an HTML form to allow for searching for students, enrolling them in classes, adding students, and adding classes.
Prerequisites
Before starting, you should have a basic understanding of JavaScript, Node.js, MongoDB, and Express.js. You should also have the following software installed on your computer:
Node.js
MongoDB
Visual Studio Code or any other code editor
Step 1: Set up the Project
Open your code editor and create a new folder for your project.
Open the terminal or command prompt and navigate to your project folder.
Initialize a new Node.js project by running the following command:
npm init -y
Install the required packages by running the following command:
npm install express mongoose body-parser ejs
express is a popular Node.js web framework that will help us create our server.
mongoose is a MongoDB object modeling tool that allows us to interact with the database.
body-parser is a middleware that will help us parse incoming request bodies.
ejs is a templating engine that will help us render HTML pages.
Create the following files and folders:
├── app.js
├── db.js
├── models/
│ └── student.js
├── public/
│ ├── css/
│ │ └── style.css
│ └── js/
│ └── script.js
└── views/
├── enroll.ejs
├── index.ejs
├── search.ejs
└── student.ejs
app.js is the main file that will contain our server logic.
db.js is the file that will contain our database connection logic.
models/student.js is the file that will define our student model.
public/css/style.css is the file that will contain our CSS styles.
public/js/script.js is the file that will contain our client-side JavaScript code.
views/enroll.ejs is the file that will contain our HTML form for enrolling students in classes.
views/index.ejs is the file that will contain our homepage HTML.
views/search.ejs is the file that will contain our HTML form for searching students.
views/student.ejs is the file that will contain our HTML form for adding students and classes.
Step 2: Set up the Database Connection
Open the db.js file and add the following code to connect to the MongoDB database: