Share
Explore

Node MONGO Express CES with a Web Form Front End

Student Enrollment System Workbook

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:
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/student-enrollment-system', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
});

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));

db.once('open', function() {
console.log('Database connected successfully');
});


Open the models/student.js file and add the following code to define the student model:

const mongoose = require('mongoose');

const studentSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
age: {
type: Number,
required: true
},
major: {
type: String,
required: true
},
classes: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Class'
}
]
});

module.exports = mongoose.model('Student', studentSchema);


We have defined a student schema with name, age, major, and classes fields.
The classes field is an array of ObjectIds that reference the Class model, which we will define later.

Step 3: Create the Server

Open the app.js file and add the following code to create the server:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const Student = require('./models/student');

const app = express();

app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));

// define routes here

const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});

We have created an Express.js app and set the view engine to ejs.
We have also set the static directory to public and used the body-parser middleware to parse incoming request bodies.
We have defined a route for the homepage (/).

Add the following code to the homepage route to render the index.ejs file:

app.get('/', (req, res) => {
res.render('index');
});


Add the following code to the index.ejs file to create a basic HTML template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Enrollment System</title>
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<h1>Student Enrollment System</h1>
</body>
</html>


Add the following code to create a route for searching students:
app.get('/search', (req, res) => {
res.render('search');
});


Add the following code to create the search.ejs file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Search Students</title>
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<h2>Search Students</h2>
<form action="/search" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<br>
<label for="major">Major:</label>
<input type="text" id="major" name="major">
<br>
<button type="submit">Search</button>
</form>
</body>
</html>


Add the following code to handle the search form submission:
app.post('/search', async (req, res) => {
const { name, major } = req.body;
const students = await Student.find({
name: new RegExp(name, 'i'),
major: new RegExp(major, 'i')
});
res.render('student', { students });
});


We have used the RegExp constructor to create a case-insensitive regular expression for searching by name and major.
We have used the find method to find all students that match the search criteria.
We have rendered the student.ejs file with the students data.

Add the following code to create a route for adding students and classes:
app.get('/add', (req, res) => {
res.render('student');
});


Add the following code to create the student.ejs file:


```html




Add Student

Name: Age: Major: Classes Add Class Save
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.