Aim
Develop a client-server application that performs Create, Read, Update and Delete (CRUD) operations on student records in MongoDB, with validated forms rendered by the server.
Stack: Node.js, Express, Mongoose, MongoDB, HTML, CSS and JavaScript.
Flow: Browser → Express route → Mongoose → MongoDB → HTML page → Browser
Quick start: first time
- Create a folder named
student-crud. - In VS Code choose File → Open Folder and select it.
- Create
package.json, copy its code from Step 2, paste and save. - Create
server.js, copy its code from Step 2, paste and save. - Connect in Compass (see Compass section) to check that MongoDB is running.
- Choose Terminal → New Terminal and run
npm install. - Run
npm startand keep the terminal open. - Open
http://localhost:3000and add a student. - Refresh Compass and open labdb → students.
Step 1: Install and set up
- Install Node.js (LTS version) from nodejs.org.
- Install MongoDB Community Server from mongodb.com and make sure its service is running. MongoDB Compass is useful for viewing the data.
- Check Node and create the project folder:
node -v npm -v mkdir student-crud cd student-crud
Things you need
| Item | Purpose | Check |
|---|---|---|
| Node.js 20.19 or later (includes npm) | Runs the server | node -v |
| MongoDB Server | Stores the data | Compass connects |
| MongoDB Compass | Views the data | Opens |
| VS Code or another editor | Edits the files | Opens |
| Browser | Uses the app | Opens |
| Internet for the first install | Downloads packages | npm install succeeds |
Step 2: Create the two files
Put both files inside the student-crud folder. Use Download, or Copy and paste into an editor.
{
"name": "student-crud",
"version": "1.0.0",
"main": "server.js",
"scripts": { "start": "node server.js" },
"dependencies": {
"express": "^5.1.0",
"mongoose": "^9.0.0"
}
}
// Student Management System: Express + MongoDB (Mongoose) + server-rendered forms
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const PORT = process.env.PORT || 3000;
const MONGO_URL = process.env.MONGO_URL || 'mongodb://127.0.0.1:27017/labdb';
const DEPARTMENTS = ['CSE', 'ECE', 'EEE', 'MECH', 'CIVIL', 'IT'];
app.use(express.urlencoded({ extended: true }));
// ---------- 1. Model with server-side validation ----------
const studentSchema = new mongoose.Schema({
rollNo: {
type: String, trim: true, unique: true,
required: [true, 'Roll No is required'],
match: [/^[A-Za-z0-9]{3,10}$/, 'Roll No must be 3 to 10 letters or digits']
},
name: {
type: String, trim: true,
required: [true, 'Name is required'],
match: [/^[A-Za-z .]{2,40}$/, 'Name must be 2 to 40 letters']
},
email: {
type: String, trim: true,
required: [true, 'Email is required'],
match: [/^[^\s@]+@[^\s@]+\.[^\s@]+$/, 'Enter a valid email']
},
dept: {
type: String,
required: [true, 'Select a department'],
enum: { values: DEPARTMENTS, message: 'Invalid department' }
},
marks: {
type: Number,
required: [true, 'Marks are required'],
min: [0, 'Marks cannot be below 0'],
max: [100, 'Marks cannot exceed 100']
}
});
const Student = mongoose.model('Student', studentSchema);
// ---------- 2. Helpers ----------
const esc = (v) => String(v ?? '').replace(/[&<>"']/g,
(c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
const fields = ({ rollNo, name, email, dept, marks } = {}) =>
({ rollNo, name, email, dept, marks });
// Convert a Mongoose error into { fieldName: message }
const toErrors = (err) => {
if (err.code === 11000) return { rollNo: 'This Roll No already exists' };
if (err.name === 'ValidationError') {
return Object.fromEntries(Object.values(err.errors).map((e) =>
[e.path, e.name === 'CastError' ? 'Enter a valid number' : e.message]));
}
throw err;
};
// ---------- 3. Views ----------
const CSS = `
* { box-sizing: border-box; }
body { margin: 0; font-family: Segoe UI, Arial, sans-serif; background: #f1f4f9; color: #1f2937; }
header { background: #1e3a8a; color: #fff; padding: 16px 24px; font-size: 20px; font-weight: 600; }
main { max-width: 900px; margin: 24px auto; padding: 0 16px; }
.card { background: #fff; border-radius: 10px; padding: 24px; box-shadow: 0 2px 8px rgba(0,0,0,.08); overflow-x: auto; }
.narrow { max-width: 480px; margin: auto; }
.bar { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 16px; }
.bar form { display: flex; gap: 8px; flex: 1; }
table { width: 100%; border-collapse: collapse; }
th, td { padding: 10px; text-align: left; border-bottom: 1px solid #e5e7eb; }
th { background: #f9fafb; }
label { display: block; font-weight: 600; margin-bottom: 4px; }
input, select { width: 100%; padding: 9px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 14px; }
.field { margin-bottom: 14px; }
.invalid { border-color: #dc2626; background: #fef2f2; }
.error { color: #dc2626; font-size: 13px; min-height: 16px; display: block; }
.btn { display: inline-block; border: 0; border-radius: 6px; padding: 9px 16px; background: #2563eb;
color: #fff; text-decoration: none; cursor: pointer; font-size: 14px; }
.grey { background: #64748b; }
.red { background: #dc2626; }
.success { background: #dcfce7; color: #166534; padding: 10px 14px; border-radius: 6px; margin-bottom: 16px; }
.actions { display: flex; gap: 6px; }
`;
const page = (title, body) => `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${title}</title>
<style>${CSS}</style>
</head>
<body>
<header>Student Management System</header>
<main>${body}</main>
</body>
</html>`;
const MESSAGES = { added: 'Student added', updated: 'Student updated', deleted: 'Student deleted' };
const listView = (students, q, msg) => page('Students', `
${Object.hasOwn(MESSAGES, msg) ? `<div class="success">${MESSAGES[msg]} successfully.</div>` : ''}
<div class="card">
<h2>Student List (${students.length})</h2>
<div class="bar">
<form method="GET" action="/">
<input name="q" placeholder="Search by name" value="${esc(q)}">
<button class="btn grey">Search</button>
</form>
<a class="btn" href="/students/new">+ Add Student</a>
</div>
<table>
<tr><th>Roll No</th><th>Name</th><th>Email</th><th>Dept</th><th>Marks</th><th>Actions</th></tr>
${students.map((s) => `
<tr>
<td>${esc(s.rollNo)}</td>
<td>${esc(s.name)}</td>
<td>${esc(s.email)}</td>
<td>${esc(s.dept)}</td>
<td>${esc(s.marks)}</td>
<td class="actions">
<a class="btn" href="/students/${s._id}/edit">Edit</a>
<form method="POST" action="/students/${s._id}/delete" onsubmit="return confirm('Delete this record?')">
<button class="btn red">Delete</button>
</form>
</td>
</tr>`).join('') || '<tr><td colspan="6">No records found</td></tr>'}
</table>
</div>`);
const formView = (title, action, s = {}, errors = {}) => {
const input = (key, label, attrs) => `
<div class="field">
<label for="${key}">${label}</label>
<input id="${key}" name="${key}" value="${esc(s[key])}" class="${errors[key] ? 'invalid' : ''}" ${attrs} required>
<span class="error">${esc(errors[key])}</span>
</div>`;
return page(title, `
<div class="card narrow">
<h2>${title}</h2>
<form id="studentForm" method="POST" action="${esc(action)}" novalidate>
${input('rollNo', 'Roll No', 'pattern="[A-Za-z0-9]{3,10}" data-msg="Use 3 to 10 letters or digits"')}
${input('name', 'Name', 'pattern="[A-Za-z .]{2,40}" data-msg="Use 2 to 40 letters"')}
${input('email', 'Email', 'type="email" data-msg="Enter a valid email"')}
<div class="field">
<label for="dept">Department</label>
<select id="dept" name="dept" class="${errors.dept ? 'invalid' : ''}" data-msg="Select a department" required>
<option value="">-- Select --</option>
${DEPARTMENTS.map((d) => `<option ${s.dept === d ? 'selected' : ''}>${d}</option>`).join('')}
</select>
<span class="error">${esc(errors.dept)}</span>
</div>
${input('marks', 'Marks', 'type="number" min="0" max="100" step="any" data-msg="Enter a number from 0 to 100"')}
<button class="btn">Save</button>
<a class="btn grey" href="/">Cancel</a>
</form>
</div>
<script>
// ---------- Client-side validation ----------
const form = document.getElementById('studentForm');
const controls = form.querySelectorAll('input, select');
function check(el) {
el.value = el.value.trim();
const ok = el.checkValidity();
el.classList.toggle('invalid', !ok);
el.nextElementSibling.textContent = ok ? '' :
(el.validity.valueMissing ? 'This field is required' : el.dataset.msg);
return ok;
}
controls.forEach((el) => el.addEventListener('change', () => check(el)));
form.addEventListener('submit', (e) => {
const results = Array.from(controls).map(check);
if (results.includes(false)) e.preventDefault();
});
</script>`);
};
// ---------- 4. CRUD routes ----------
// READ
app.get('/', async (req, res) => {
const q = String(req.query.q || '').trim();
const safe = q.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const filter = q ? { name: { $regex: safe, $options: 'i' } } : {};
const students = await Student.find(filter).sort({ rollNo: 1 });
res.send(listView(students, q, req.query.msg));
});
// CREATE
app.get('/students/new', (req, res) => res.send(formView('Add Student', '/students')));
app.post('/students', async (req, res) => {
try {
await Student.create(fields(req.body));
res.redirect('/?msg=added');
} catch (err) {
res.status(400).send(formView('Add Student', '/students', fields(req.body), toErrors(err)));
}
});
// UPDATE
app.get('/students/:id/edit', async (req, res) => {
const s = await Student.findById(req.params.id);
if (!s) return res.status(404).send('Student not found');
res.send(formView('Edit Student', `/students/${s._id}`, s));
});
app.post('/students/:id', async (req, res) => {
try {
const s = await Student.findByIdAndUpdate(req.params.id, fields(req.body), { runValidators: true });
if (!s) return res.status(404).send('Student not found');
res.redirect('/?msg=updated');
} catch (err) {
if (err.name === 'CastError') throw err;
res.status(400).send(formView('Edit Student', `/students/${encodeURIComponent(req.params.id)}`,
fields(req.body), toErrors(err)));
}
});
// DELETE
app.post('/students/:id/delete', async (req, res) => {
await Student.findByIdAndDelete(req.params.id);
res.redirect('/?msg=deleted');
});
// ---------- 5. Error handler and start ----------
app.use((err, req, res, next) => {
console.error(err.message);
if (err.name === 'CastError') return res.status(400).send('Invalid id');
res.status(500).send('Something went wrong');
});
mongoose.connect(MONGO_URL)
.then(() => app.listen(PORT, () => console.log(`Running at http://localhost:${PORT}`)))
.catch((err) => console.error('MongoDB connection failed:', err.message));
Folder structure
student-crud/ package.json (you create) server.js (you create) node_modules/ (created by npm install) package-lock.json (created by npm install)
Purpose of package.json
It describes the project, lists the packages it needs and says how to start it.
| Entry | Meaning |
|---|---|
| name, version | Project name and version |
| main | Main code file |
| scripts → start | npm start runs node server.js |
| dependencies | Packages that npm install downloads |
| express | Web server and routes |
| mongoose | Connects to MongoDB |
| ^5.1.0 | 5.1.0 or a newer 5.x release |
Shortcut: let npm create package.json
Create server.js yourself, then run:
npm init -y npm install express mongoose node server.js
Connect with MongoDB Compass
Compass is a viewer; the MongoDB server must also be running.
- Open Compass and click Add new connection.
- Enter the address below and click Connect.
mongodb://127.0.0.1:27017
| Part | Meaning |
|---|---|
| mongodb:// | MongoDB protocol |
| 127.0.0.1 | Your own computer |
| 27017 | Default MongoDB port |
| /labdb (in server.js) | Database used by the app |
This is the default local address. It will differ if your lab uses another port, a login, a lab server or Atlas; then use the string your lab gives you in both Compass and MONGO_URL in server.js.
With a login, the format is mongodb://username:password@127.0.0.1:27017/labdb?authSource=admin
Check the port on Windows: a line with LISTENING means a program is waiting on it.
netstat -ano | findstr 27017
The app connects by itself, so Compass need not stay open. The labdb database appears once the app has connected and saved data; refresh to see it.
Step 3: Run
Run these inside the project folder:
npm install npm start
Open http://localhost:3000 in the browser. Press Ctrl + C to stop the server.
For MongoDB Atlas, set the MONGO_URL environment variable to your connection string before starting.
When is npm install needed?
| Situation | Run npm install? |
|---|---|
| First setup of the folder | Yes |
| Running the app again | No, only npm start |
| After editing server.js | No, press Ctrl + C, then npm start |
| node_modules deleted or not copied | Yes |
| New package added to package.json | Yes |
Step 4: Perform the CRUD operations
| Operation | What to do | Route | Mongoose method |
|---|---|---|---|
| Create | Click + Add Student, fill the form, click Save | GET /students/new POST /students | create() |
| Read | Open the home page, or search by name | GET / GET /?q=name | find().sort() |
| Update | Click Edit, change values, click Save | GET /students/:id/edit POST /students/:id | findById() findByIdAndUpdate() |
| Delete | Click Delete and confirm | POST /students/:id/delete | findByIdAndDelete() |
Verify in the database using the MongoDB shell:
mongosh use labdb db.students.find()
How the code works
The browser never talks to MongoDB directly: Browser ↔ Node and Express ↔ MongoDB.
app.get('/', async (req, res) => {
// search filter is prepared here
const students = await Student.find(filter).sort({ rollNo: 1 }); // fetch from DB
res.send(listView(students, q, req.query.msg)); // build and send HTML
});- The browser requests the Add form.
- You click Save, which sends a POST request.
express.urlencoded()fillsreq.body.Student.create()validates and saves.- On success the server redirects to the list, which fetches the data again. On failure the form returns with errors.
| Code | Meaning |
|---|---|
| req.params.id | Value from the URL path |
| req.query.q | Value after ? in the URL |
| req.body | Submitted form data |
| res.send() / res.redirect() | Send a page / go to another URL |
| 200, 302, 400, 404, 500 | Success, redirect, bad input, not found, server error |
One line for the viva: It is a client-server web application that performs CRUD operations on student records in MongoDB, using Express and Mongoose, with pages and forms rendered by the server.
Form validation
| Field | Rule | Sample invalid input |
|---|---|---|
| Roll No | Required, 3 to 10 letters or digits, unique | 1, or a repeated number |
| Name | Required, 2 to 40 letters, spaces or dots | A1 |
| Required, valid format | asha@ | |
| Department | Required, chosen from the list | Nothing selected |
| Marks | Required, 0 to 100 | 150 |
Client side: HTML attributes and a short script show messages under each field before submission.
Server side: the Mongoose schema checks the data again, because browser checks can be bypassed. The unique index catches repeated roll numbers (error code 11000).
Sample valid record: 21CS01, Asha Kumar, asha@example.com, CSE, 88
Concepts used
| Concept | Meaning |
|---|---|
| Client and server | The browser sends requests; the Node program responds. |
| GET and POST | GET fetches a page; POST submits data that changes something. |
| Express route | A function that runs for a given method and URL. |
| Middleware | Code that processes a request; express.urlencoded() fills req.body. |
| Schema and model | The schema defines fields and rules; the model queries the collection. |
| Document and collection | Similar to a row and a table in SQL. |
| async / await | Waits for a database result without blocking other requests. |
| Server-side rendering | The server builds the HTML using template literals. |
| Post/Redirect/Get | Redirecting after saving prevents resubmission on refresh. |
| XSS protection | esc() stops user input from running as HTML or script. |
Viva questions
Why is POST used for update and delete?
HTML forms support only GET and POST.
What is _id?
The unique key of each MongoDB document.
Why is runValidators: true needed?
Mongoose does not run schema validators on updates by default.
What is Mongoose?
An object data modelling library for MongoDB in Node.js.
What does novalidate do?
It turns off the browser's default popups so the script can show its own messages.
What is the difference between req.params, req.query and req.body?
Values from the URL path, the query string and the submitted form.
Troubleshooting
| Problem | Fix |
|---|---|
| MongoDB connection failed (ECONNREFUSED) | Start the MongoDB service. |
| Cannot find module 'express' | Run npm install in the project folder. |
| EADDRINUSE: port 3000 | Stop the other program or set a different PORT. |
| npm is not recognized | Install Node.js and reopen the terminal. |
| Duplicate roll numbers are accepted | Remove existing duplicates, then restart so the unique index can be built. |
More fixes
| Problem | Fix |
|---|---|
| VS Code says running scripts is disabled | Use npm.cmd install and npm.cmd start. |
| File saved as server.js.txt | Rename it so it ends in .js (or .json). |
| No MongoDB service on Windows | Open services.msc and look for MongoDB Server. If absent, run mongod.exe as below, or install MongoDB Community Server. |
| npm install fails with no internet | Install beforehand and copy the whole folder, if your test rules allow it. |
net start MongoDB REM or, without a service (replace <version>): mkdir C:\data\db "C:\Program Files\MongoDB\Server\<version>\bin\mongod.exe" --dbpath C:\data\db