Share
Explore

The MONGO DB College Enrollment System

Here is how this would be done in SQL:


Below is a complete program that demonstrates how to create a College Enrollment System using Mongoose and a local MongoDB server.


The program includes:

defining JSON schemas : schema is JavaScript class which we use to make JSON data documents
CREATE JSON records: inserting sample data,
update, delete operations work with getting a handle on a set of JSON data documents using a FIELD FILTER
Do predicate join between collections using the aggregation pipeline to register students into classes.

Step-by-Step Guide

1. **Set Up MongoDB and Mongoose**: Make sure you have MongoDB installed and running on your local premises. Install Mongoose in your project directory.
Make a new project (new directory) in VSC npm init -y npm install mongoose ```
2. Create the Project Structure**: Create the following files in your project directory: - `models.js` - `insertData.js` - `enrollStudents.js` - `aggregateEnrollments.js`

`models.js`

const mongoose = require('mongoose');
const studentSchema = new mongoose.Schema(
{ studentId: String, firstName: String, lastName: String, program: String, term: String },
{ collection: 'students' }
);
const classSchema = new mongoose.Schema({ classId: String, courseName: String, dateTime: String, instructorId: String, location: String }, { collection: 'classes' });
const enrollmentSchema = new mongoose.Schema({ enrollmentId: String, studentId: String, classId: String }, { collection: 'enrollments' });
const Student = mongoose.model('Student', studentSchema); const Class = mongoose.model('Class', classSchema); const Enrollment = mongoose.model('Enrollment', enrollmentSchema);
module.exports = { Student, Class, Enrollment }; ```




insertData.js


const mongoose = require('mongoose'); const { Student, Class } = require('./models');
// MongoDB Local URI const uri = "mongodb://localhost:27017/college";
// Connect to MongoDB mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log('Connected to MongoDB'); insertData(); }) .catch((err) => { console.error('Connection error', err); });
const insertData = async () => { const students = [ { studentId: 'S001', firstName: 'Joe', lastName: 'Smith', program: 'Computer Science', term: 'Fall' }, { studentId: 'S002', firstName: 'Suzan', lastName: 'Ross', program: 'Engineering', term: 'Fall' }, { studentId: 'S003', firstName: 'Peanut', lastName: 'Bindger', program: 'Mathematics', term: 'Fall' }, { studentId: 'S004', firstName: 'Mark', lastName: 'Jenkins', program: 'Physics', term: 'Fall' }, { studentId: 'S005', firstName: 'Alice', lastName: 'Johnson', program: 'Biology', term: 'Fall' }, { studentId: 'S006', firstName: 'Bob', lastName: 'Brown', program: 'Chemistry', term: 'Fall' }, { studentId: 'S007', firstName: 'Charlie', lastName: 'Davis', program: 'Quantum Computing', term: 'Fall' }, { studentId: 'S008', firstName: 'Dana', lastName: 'Miller', program: 'Artificial Intelligence', term: 'Fall' }, { studentId: 'S009', firstName: 'Eve', lastName: 'White', program: 'Astrogation', term: 'Fall' }, { studentId: 'S010', firstName: 'Frank', lastName: 'Green', program: 'Computational Biology', term: 'Fall' }, { studentId: 'S011', firstName: 'Grace', lastName: 'Taylor', program: 'Computational Materials', term: 'Fall' }, { studentId: 'S012', firstName: 'Hank', lastName: 'Wilson', program: 'Artificial Intelligence', term: 'Fall' }, { studentId: 'S013', firstName: 'Ivy', lastName: 'Moore', program: 'Quantum Computing', term: 'Fall' }, { studentId: 'S014', firstName: 'Jack', lastName: 'Anderson', program: 'Astrogation', term: 'Fall' }, { studentId: 'S015', firstName: 'Kate', lastName: 'Thomas', program: 'Computational Biology', term: 'Fall' }, { studentId: 'S016', firstName: 'Leo', lastName: 'Harris', program: 'Computational Materials', term: 'Fall' }, { studentId: 'S017', firstName: 'Mona', lastName: 'Martinez', program: 'Artificial Intelligence', term: 'Fall' }, { studentId: 'S018', firstName: 'Nina', lastName: 'Clark', program: 'Quantum Computing', term: 'Fall' }, { studentId: 'S019', firstName: 'Owen', lastName: 'Lewis', program: 'Astrogation', term: 'Fall' }, { studentId: 'S020', firstName: 'Paul', lastName: 'Lee', program: 'Computational Biology', term: 'Fall' } ];
const classes = [ { classId: 'C001', courseName: 'Quantum Computing 101', dateTime: 'Mon 9AM', instructorId: 'I001', location: 'Room 101' }, { classId: 'C002', courseName: 'Galactic Astrogation 101', dateTime: 'Wed 11AM', instructorId: 'I002', location: 'Room 102' }, { classId: 'C003', courseName: 'Computational Biology 101', dateTime: 'Fri 2PM', instructorId: 'I003', location: 'Room 103' }, { classId: 'C004', courseName: 'Computational Materials 101', dateTime: 'Tue 10AM', instructorId: 'I004', location: 'Room 104' }, { classId: 'C005', courseName: 'Artificial Intelligence Engineering 101', dateTime: 'Thu 3PM', instructorId: 'I005', location: 'Room 105' }, { classId: 'C006', courseName: 'Astrophysics 101', dateTime: 'Mon 1PM', instructorId: 'I006', location: 'Room 106' } ];
try { await Student.insertMany(students); await Class.insertMany(classes); console.log('Sample data inserted'); } catch (err) { console.error('Error inserting data:', err); } finally { mongoose.connection.close().then(() => { console.log('Mongoose connection closed'); }).catch(err => { console.error('Error closing connection:', err); }); } }; ```

`enrollStudents.js`

const mongoose = require('mongoose'); const { Enrollment } = require('./models');
// MongoDB Local URI const uri = "mongodb://localhost:27017/college";
// Connect to MongoDB mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log('Connected to MongoDB'); enrollStudents(); }) .catch((err) => { console.error('Connection error', err); });
const enrollStudents = async () => { const enrollments = [ { enrollmentId: 'E001', studentId: 'S001', classId: 'C001' }, { enrollmentId: 'E002', studentId: 'S001', classId: 'C002' }, { enrollmentId: 'E003', studentId: 'S002', classId: 'C001' }, { enrollmentId: 'E004', studentId: 'S003', classId: 'C003' }, { enrollmentId: 'E005', studentId: 'S004', classId: 'C004' }, { enrollmentId: 'E006', studentId: 'S005', classId: 'C005' }, { enrollmentId: 'E007', studentId: 'S006', classId: 'C006' }, { enrollmentId: 'E008', studentId: 'S007', classId: 'C001' }, { enrollmentId: 'E009', studentId: 'S008', classId: 'C005' }, { enrollmentId: 'E010', studentId: 'S009', classId: 'C002' }, { enrollmentId: 'E011', studentId: 'S010', classId: 'C003' }, { enrollmentId: 'E012', studentId: 'S011', classId: 'C004' }, { enrollmentId: 'E013', studentId: 'S012', classId: 'C005' }, { enrollmentId: 'E014', studentId: 'S013', classId: 'C001' }, { enrollmentId: 'E015', studentId: 'S014', classId: 'C002' }, { enrollmentId: 'E016', studentId: 'S015', classId: 'C003' }, { enrollmentId: 'E017', studentId: 'S016', classId: 'C004' }, { enrollmentId: 'E018', studentId: 'S017', classId: 'C005' },
{ enrollmentId: 'E019', studentId: 'S018', classId: 'C001' }, { enrollmentId: 'E020', studentId: 'S019', classId: 'C002' }, { enrollmentId: 'E021', studentId: 'S020', classId: 'C003' } ];
try { await Enrollment.insertMany(enrollments); console.log('Students enrolled into classes'); } catch (err) { console.error('Error enrolling students:', err); } finally { mongoose.connection.close().then(() => { console.log('Mongoose connection closed'); }).catch(err => { console.error('Error closing connection:', err); }); } }; ```

`aggregateEnrollments.js`


const mongoose = require('mongoose'); const { Enrollment } = require('./models');
// MongoDB Local URI const uri = "mongodb://localhost:27017/college";
// Connect to MongoDB mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('Connected to MongoDB')) .catch((err) => console.error('Connection error', err));
const aggregateEnrollments = async () => { try { const result = await Enrollment.aggregate([ { $lookup: { from: 'students', localField: 'studentId', foreignField: 'studentId', as: 'studentDetails' } }, { $lookup: { from: 'classes', localField: 'classId', foreignField: 'classId', as: 'classDetails' } }, { $unwind: '$studentDetails' }, { $unwind: '$classDetails' }, { $project: { _id: 0, enrollmentId: 1, 'studentDetails.firstName': 1, 'studentDetails.lastName': 1, 'classDetails.courseName': 1, 'classDetails.dateTime': 1, 'classDetails.location': 1 } } ]);
console.log('Aggregated Enrollments:', JSON.stringify(result, null, 2)); } catch (err) { console.error('Error aggregating enrollments:', err); } finally { mongoose.connection.close().then(() => { console.log('Mongoose connection closed'); }).catch(err => { console.error('Error closing connection:', err); }); } };
aggregateEnrollments(); ```


Running the Programs

1. **Insert Sample Data**: ```bash node insertData.js ```
2. **Enroll Students into Classes**: ```bash node enrollStudents.js ```
3. **Aggregate Enrollments**: ```bash node aggregateEnrollments.js ```
This program demonstrates how to create a College Enrollment System with MongoDB and Mongoose on a local premises server, including inserting sample data, enrolling students into classes, and using the aggregation pipeline to register students into classes.

megaphone

Lab Part 2: Bolting on the Front End HTTP Server


Lab Lesson: Building a College Enrollment System with MongoDB and Express.js
#### Objective In this lesson, students will learn how to create a College Enrollment System using MongoDB, Mongoose, and Express.js.
The system will include functionality for adding, updating, and deleting student records through an Express.js web server with HTML forms.
### Table of Contents 1. Set Up MongoDB and Mongoose 2. Create Project Structure 3. Define Mongoose Schemas 4. Insert Sample Data 5. Create Express.js Web Server 6. Create HTML Forms for CRUD Operations 7. Demonstrate Predicate Join with Aggregation Pipeline 8. Running and Testing the Application
---

1. Set Up MongoDB and Mongoose

Ensure MongoDB is installed and running on your local machine.
Initialize a new Node.js project and install required packages:
```bash mkdir collegeEnrollmentApp cd collegeEnrollmentApp npm init -y npm install express mongoose body-parser ejs ```
### 2. Create Project Structure
Create the following files and directories: - `models.js` - `insertData.js` - `enrollStudents.js` - `aggregateEnrollments.js` - `app.js` - `views/` - index.ejs`` - `addStudent.ejs` - `editStudent.ejs`

3. Define Mongoose Schemas: DONE: Create `models.js`:
```javascript const mongoose = require('mongoose');
const studentSchema = new mongoose.Schema({ studentId: String, firstName: String, lastName: String, program: String, term: String }, { collection: 'students' });
const classSchema = new mongoose.Schema({ classId: String, courseName: String, dateTime: String, instructorId: String, location: String }, { collection: 'classes' });
const enrollmentSchema = new mongoose.Schema({ enrollmentId: String, studentId: String, classId: String }, { collection: 'enrollments' });
const Student = mongoose.model('Student', studentSchema); const Class = mongoose.model('Class', classSchema); const Enrollment = mongoose.model('Enrollment', enrollmentSchema);
module.exports = { Student, Class, Enrollment }; ```

DONE: 4. Insert Sample Data

Create `insertData.js`:
```javascript const mongoose = require('mongoose'); const { Student, Class } = require('./models');
// MongoDB Local URI const uri = "mongodb://localhost:27017/college";
// Connect to MongoDB mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log('Connected to MongoDB'); insertData(); }) .catch((err) => { console.error('Connection error', err); });
const insertData = async () => { const students = [ { studentId: 'S001', firstName: 'Joe', lastName: 'Smith', program: 'Computer Science', term: 'Fall' }, { studentId: 'S002', firstName: 'Suzan', lastName: 'Ross', program: 'Engineering', term: 'Fall' }, // Add more students as needed... ];
const classes = [ { classId: 'C001', courseName: 'Quantum Computing 101', dateTime: 'Mon 9AM', instructorId: 'I001', location: 'Room 101' }, { classId: 'C002', courseName: 'Galactic Astrogation 101', dateTime: 'Wed 11AM', instructorId: 'I002', location: 'Room 102' }, // Add more classes as needed... ];
try { await Student.insertMany(students); await Class.insertMany(classes); console.log('Sample data inserted'); } catch (err) { console.error('Error inserting data:', err); } finally { mongoose.connection.close().then(() => { console.log('Mongoose connection closed'); }).catch(err => { console.error('Error closing connection:', err); }); } }; ```

5. Create Express.js Web Server

Create `app.js`:
```javascript const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const { Student } = require('./models');
const app = express(); const uri = "mongodb://localhost:27017/college";
// Connect to MongoDB mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('Connected to MongoDB')) .catch(err => console.error('Could not connect to MongoDB...', err));
// Middleware app.use(bodyParser.urlencoded({ extended: true })); app.set('view engine', 'ejs');
// Routes app.get('/', async (req, res) => { const students = await Student.find(); res.render('index', { students }); });
app.get('/student/add', (req, res) => { res.render('addStudent'); });
app.post('/student/add', async (req, res) => { const { studentId, firstName, lastName, program, term } = req.body; const newStudent = new Student({ studentId, firstName, lastName, program, term }); await newStudent.save(); res.redirect('/'); });
app.get('/student/edit/:id', async (req, res) => { const student = await Student.findById(req.params.id); res.render('editStudent', { student }); });
app.post('/student/edit/:id', async (req, res) => { const { studentId, firstName, lastName, program, term } = req.body; await Student.findByIdAndUpdate(req.params.id, { studentId, firstName, lastName, program, term }); res.redirect('/'); });
app.post('/student/delete/:id', async (req, res) => { await Student.findByIdAndDelete(req.params.id); res.redirect('/'); });
// Start Server const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`Server is running on port ${port}`); }); ```

6. Create HTML Forms for CRUD Operations

Create `views/index.ejs`:
```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>College Enrollment System</title> </head> <body> <h1>Student List</h1> <a href="/student/add">Add New Student</a> <ul> <% students.forEach(student => { %> <li> <%= student.firstName %> <%= student.lastName %> - <%= student.program %> (<%= student.term %>) <a href="/student/edit/<%= student._id %>">Edit</a> <form action="/student/delete/<%= student._id %>" method="POST" style="display:inline;"> <button type="submit">Delete</button> </form> </li> <% }) %> </ul> </body> </html> ```
Create `views/addStudent.ejs`:
```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Add New Student</title> </head> <body> <h1>Add New Student</h1> <form action="/student/add" method="POST"> <label for="studentId">Student ID:</label> <input type="text" id="studentId" name="studentId" required><br> <label for="firstName">First Name:</label> <input type="text" id="firstName" name="firstName" required><br> <label for="lastName">Last Name:</label> <input type="text" id="lastName" name="lastName" required><br> <label for="program">Program:</label> <input type="text" id="program" name="program" required><br> <label for="term">Term:</label> <input type="text" id="term" name="term" required><br> <button type="submit">Add Student</button> </form> <a href="/">Back to Student List</a> </body> </html> ```
Create `views/editStudent.ejs`:
```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Edit Student</title> </head> <body> <h1>Edit Student</h1> <form action="/student/edit/<%= student._id %>" method="POST"> <label for="studentId">Student ID:</label> <input type="text" id="studentId" name="studentId" value="<%= student.studentId %>" required><br> <label for="firstName">First Name:</label> <input type="text" id="firstName" name="firstName" value="<%= student.firstName %>" required><br> <label for="lastName">Last Name:</label> <input type="text" id="lastName" name="lastName" value="<%= student.lastName %>" required><br> <label for="program">Program
:</label> <input type="text" id="program" name="program" value="<%= student.program %>" required><br> <label for="term">Term:</label> <input type="text" id="term" name="term" value="<%= student.term %>" required><br> <button type="submit">Update Student</button> </form> <a href="/">Back to Student List</a> </body> </html> ```
DONE: Step 7. Demonstrate Predicate Join with Aggregation Pipeline
Create `aggregateEnrollments.js`:
```javascript const mongoose = require('mongoose'); const { Enrollment } = require('./models');
// MongoDB Local URI const uri = "mongodb://localhost:27017/college";
// Connect to MongoDB mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('Connected to MongoDB')) .catch((err) => console.error('Connection error', err));
const aggregateEnrollments = async () => { try { const result = await Enrollment.aggregate([ { $lookup: { from: 'students', localField: 'studentId', foreignField: 'studentId', as: 'studentDetails' } }, { $lookup: { from: 'classes', localField: 'classId', foreignField: 'classId', as: 'classDetails' } }, { $unwind: '$studentDetails' }, { $unwind: '$classDetails' }, { $project: { _id: 0, enrollmentId: 1, 'studentDetails.firstName': 1, 'studentDetails.lastName': 1, 'classDetails.courseName': 1, 'classDetails.dateTime': 1, 'classDetails.location': 1 } } ]);
console.log('Aggregated Enrollments:', JSON.stringify(result, null, 2)); } catch (err) { console.error('Error aggregating enrollments:', err); } finally { mongoose.connection.close().then(() => { console.log('Mongoose connection closed'); }).catch(err => { console.error('Error closing connection:', err); }); } };
aggregateEnrollments(); ```

Step 8. Running and Testing the Application

1. **Insert Sample Data**: ```bash node insertData.js ```
2. **Enroll Students into Classes**: ```bash node enrollStudents.js ```
3. **Start the Express.js Server**: ```bash node app.js ```
4. **Open Browser**: - Go to `http://localhost:3000/` to view the student list. - Add a new student using the form at `http://localhost:3000/student/add`. - Edit a student using the edit link in the student list. - Delete a student using the delete button in the student list.
5. **Run Aggregation**: ```bash node aggregateEnrollments.js ```
By following these steps, students will gain hands-on experience in building a full-stack application using MongoDB, Mongoose, and Express.js, and will understand how to manage data and perform operations using HTML forms and the aggregation pipeline.

image.png

Next steps:

Add routes for other Student Enrollment Management and reporting Functions
Add to the Application base to include functionality to display room utilization and availability by day/time
How would you go about adding a Calendar display for Classes and Students?

Here are some notable calendar display libraries that you can use for simple HTML web displays:


CSS-Only Colorful Calendar Concept - Designed with vibrant colors and only utilizing HTML and CSS, this calendar provides an exciting art style and smooth scrolling functionality [citation:2][citation:10]. ```html <div class="calendar"> <div class="month"> <ul> <li class="prev">&#10094;</li> <li class="next">&#10095;</li> <li>August<br><span style="font-size:18px">2023</span></li> </ul> </div> <ul class="weekdays"> <li>Mo</li> <li>Tu</li> <li>We</li> <li>Th</li> <li>Fr</li> <li>Sa</li> <li>Su</li> </ul> <ul class="days"> <!-- Dates will go here --> </ul> </div> ```
3. **Event Calendar Widget** - Displays upcoming events clearly beneath the calendar itself, making it easy to navigate to desired dates with a sleek and simple user experience [citation:10].
4. **JavaScript Libraries - **FullCalendar.js:
A powerful and versatile JavaScript library that supports calendar views, date and event management, and integration with various frameworks like React, Angular, and Vue [citation:8][citation:6]. ```html <link href='https://unpkg.com/@fullcalendar/core/main.css' rel='stylesheet' /> <link href='https://unpkg.com/@fullcalendar/daygrid/main.css' rel='stylesheet' /> <script src='https://unpkg.com/@fullcalendar/core/main.js'></script> <script src='https://unpkg.com/@fullcalendar/daygrid/main.js'></script>
<div id='calendar'></div>
<script> document.addEventListener('DOMContentLoaded', function() { var calendarEl = document.getElementById('calendar'); var calendar = new FullCalendar.Calendar(calendarEl, { plugins: [ 'dayGrid' ], defaultView: 'dayGridMonth', events: [ { title: 'Event 1', start: '2023-07-01' }, { title: 'Event 2', start: '2023-07-02' } ] }); calendar.render(); }); </script> ``` FullCalendar provides extensive customization options, theming, and responsive designs, making it suitable for complex calendar needs [citation:8].
### 5. **DayPilot Lite** - An open-source JavaScript calendar and scheduler library with drag-and-drop functionality, ideal for creating project management and booking applications [citation:8]. ### 6. **Webix JS Calendar** - A highly customizable JavaScript library allowing users to choose specific days, months, years, and time selections. It ensures easy localization and adapts to different regions [citation:6].
These libraries and methods offer various levels of customization and functionality, ensuring that you can find one that best suits your needs for simple HTML web calendar displays.
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.