Open In App

Student Management System using Express.js and EJS Templating Engine

Last Updated : 04 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we build a student management student which will have features like adding students to a record, removing students, and updating students. We will be using popular web tools NodeJS, Express JS, and MongoDB for the backend. For the front end, we will use HTML, CSS, and JavaScript. We’ll go through every step to create this application.

Output Preview: Let us have a look at how the final output will look like

Screenshot-2024-02-28-220508

Prerequisites:

Approaches To Create Student Management System:

  • allStudents.ejs: Displays all student records.
  • add-student-form.ejs: Form for adding a new student.
  • modify-student-form.ejs: Form for updating student information.
  • deleteStudent.ejs: Form for deleting a student.
  • Navigation bar with links for viewing all students, adding, removing, and updating student information.
  • Routes for displaying, adding, modifying, and deleting students.
  • MongoDB integration using Mongoose to perform CRUD operations.
  • Error handling for cases like no matching documents found.
  • Connects to MongoDB using Mongoose.
  • Defines a students_collection schema for student records.
  • CRUD operations using the Student model.
  • Forms for user input when adding, updating, or deleting students.
  • Displays an error message if no matching documents are found.

Steps to Create Student Management System using ExpressJS and NodeJS:

Step 1: Create a server using the following command in your terminal.

npm init -y

Step 2: Install the necessary package in your application using the following command.

npm install express mongoose ejs

Step 3: Open MongoDB Atlas, and get the connection string using which we will connect our NodeJS application with MongoDB and perform CRUD operations. To get the connection string, go to Database in MongoDB atlas dashboard, then click on connect.

Project Structure:

Screenshot-2024-02-28-215410

The updated dependencies in package.json file will look like:

"dependencies": {
"express": "^4.18.2",
"ejs": "^3.1.9",
}

Example: Below is an example of Student management system using ExpressJS and NodeJS.

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>All Students</title>
    <link rel="stylesheet" href="/style.css">
</head>
<body>
    <nav>
        <a href="/">All Students</a>
        <a href="/addStudent">Add Student</a>
        <a href="/removeStudent">Remove Student</a>
        <a href="/modify">Update Student</a>
      </nav>
    <h1 style="text-align: center;">All Students</h1>
    
    <% for(let student of studentsList)  { %>
        <% if(studentsList.length===0)  { %>
            <p id="err">ERROR: No matching Document found.</p>
            <% } else { %>
                <div class="all-students-container">
                    <p>Name: <%= student.name %> </p>
                    <p>Email: <%= student.email %> </p>
                    <a href="/details">Student ID: <%= student.id %></a>
                    <p>GPA: <%= student.gpa %></p>
                   </div>
                <% } %>
    
        <% } %>
</body>
</html>


HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Student</title>
    <link rel="stylesheet" href="/style.css">
</head>
 
<body>
    <nav>
        <a href="/">All Students</a>
        <a href="/addStudent">Add Student</a>
        <a href="/removeStudent">Remove Student</a>
        <a href="/modify">Update Student</a>
    </nav>
    <h1>Add a student</h1>
    <div class="add-student-container">
        <form method="POST" action="/insert">
            <input type="text" name="studentId" placeholder="Enter student id">
            <input type="text" name="studentName" placeholder="Enter student name">
            <input type="text" name="studentGPA" placeholder="Enter student GPA">
 
            <div id="pg-container">
                <label>Post Graduate Student:</label>
 
                <input type="radio" name="studentPGStatus" value="yes">
                <label>Yes</label>
 
                <input type="radio" name="studentPGStatus" value="no">
                <label>No</label>
 
            </div>
            <button>Add student</button>
        </form>
    </div>
</body>
 
</html>


HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Modify Student</title>
  <link rel="stylesheet" href="/style.css">
</head>
 
<body>
  <nav>
    <a href="/">All Students</a>
    <a href="/addStudent">Add Student</a>
    <a href="/removeStudent">Remove Student</a>
    <a href="/modify">Update Student</a>
  </nav>
  <h1>Update Student Information</h1>
  <div class="modify-student">
    <% for (let currItem of students) { %>
      <div class="modify-student-container">
        <form action="/change/<%= currItem._id %>" method="POST">
 
          <label>Student Name: <%= currItem.name%></label>
 
          <label>Student Id</label>
          <input type="text" value="<%= currItem.id %>" name="studentId" readonly />
 
          <label>GPA:</label>
          <input type="text" value="<%= currItem.gpa %>" name="updatedGPA" />
 
          <button>Submit</button>
        </form>
      </div>
      <% } %>
  </div>
</body>
</html>


HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Delete Student</title>
    <link rel="stylesheet" href="/style.css">
</head>
<body>
    <nav>
        <a href="/">All Students</a>
        <a href="/addStudent">Add Student</a>
        <a href="/removeStudent">Remove Student</a>
        <a href="/modify">Update Student</a>
      </nav>
    <h1>Delete Student Information</h1>
   <div style="width: 40%;
   background-color: #eeedeb;
   margin: auto;
   border-radius: 20px;
   padding: 20px;">
    <% for (let currItem of students) { %>
        <form action="/delete/<%= currItem._id %>" method="POST">
             
            <div style="display: flex;justify-content: space-evenly;margin: 10px;">
                <label>Student Name: <%= currItem.name%></label>  
            <button>Delete</button>
            </div>
        </form>
    <% } %>
   </div>
 
</body>
</html>


Javascript




const express = require("express");
const app = express()
 
const mongoose = require('mongoose');
const PORT = 3000;
app.set("view engine", "ejs")
app.use(express.urlencoded({ extended: true }))
app.use(express.static("public"))
 
const url = "YOUR_MONGODB_CONNECTION_STRING"
const connectToDatabase = async () => {
    try {
        await mongoose.connect(url, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
        });
        console.log('Connected to MongoDB');
    } catch (error) {
        console.error('Error connecting to MongoDB: ', error);
    }
};
 
connectToDatabase();
 
const studentSchema = mongoose.Schema({
    id: Number,
    name: String,
    email: String,
    gpa: Number,
    isPG: Boolean
})
 
const Student = mongoose.model('students_collection', studentSchema)
 
app.get("/", async (req, res) => {
    try {
        const students = await Student.find()
        console.log(JSON.stringify(students))
        return res.render("allStudents.ejs", { studentsList: students })
    }
    catch (err) {
        return res.send(`ERROR: with all endpoint - ${err}`)
    }
})
 
 
app.get("/addStudent", (req, res) => {
    return res.render("add-student-form")
})
 
app.post("/insert", async (req, res) => {
 
    let status = false;
    if (req.body.studentPGStatus === "yes") {
        status = true
    } else {
        status = false
    }
 
    const myEmail = `${req.body.studentName}@college.com`
    const studentInfo = {
        id: parseInt(req.body.studentId),
        name: req.body.studentName,
        email: myEmail,
        gpa: parseFloat(req.body.studentGPA),
        isPG: status
    }
 
    const studentToAdd = new Student(studentInfo)
    try {
        const savedStudent = await studentToAdd.save()
 
    } catch (err) {
        console.log(err)
    }
 
    return res.redirect("/")
 
})
 
app.get("/modify", async (req, res) => {
    try {
        const students = await Student.find()
        return res.render("modify-student-form.ejs", { students: students })
    }
    catch (err) {
        console.log(err)
    }
})
 
app.post("/change/:docId", async (req, res) => {
 
    try {
        await Student.findByIdAndUpdate(req.params.docId, { gpa: req.body.updatedGPA })
        return res.redirect("/")
    }
    catch {
        return res.send(`ERROR: Cannot find student with ${req.params.id}`)
    }
 
 
})
 
app.get("/removeStudent", async (req, res) => {
 
    try {
        const students = await Student.find()
        res.render("deleteStudent.ejs", { students: students })
    }
    catch (err) {
        return res.send(`ERROR: with all endpoint - ${err}`)
    }
 
})
 
app.post("/delete/:docId", async (req, res) => {
    try {
        await Student.findByIdAndDelete(req.params.docId)
        return res.redirect("/")
    }
    catch (err) {
        console.log(`ERROR: ${err}`)
    }
 
})
 
app.get("/search", (req, res) => {
    res.render("search-form")
})
 
app.post("/find", async (req, res) => {
 
    const results = await Student.find({ name: req.body.studentName })
    if (results.length === 0) {
        return res.send(`There are no matching students`)
    } else {
        return res.send(JSON.stringify(results))
    }
})
 
app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`)
})


Start your application using the following command.

node server.js

Output:

All-Students---Google-Chrome-2024-02-18-16-56-10

Output



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads