Lab Test 2: Client-Server CRUD with MongoDB

Student Management System: code and instructions

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

  1. Create a folder named student-crud.
  2. In VS Code choose File → Open Folder and select it.
  3. Create package.json, copy its code from Step 2, paste and save.
  4. Create server.js, copy its code from Step 2, paste and save.
  5. Connect in Compass (see Compass section) to check that MongoDB is running.
  6. Choose Terminal → New Terminal and run npm install.
  7. Run npm start and keep the terminal open.
  8. Open http://localhost:3000 and add a student.
  9. Refresh Compass and open labdb → students.

Step 1: Install and set up

  1. Install Node.js (LTS version) from nodejs.org.
  2. Install MongoDB Community Server from mongodb.com and make sure its service is running. MongoDB Compass is useful for viewing the data.
  3. Check Node and create the project folder:
Terminal
node -v
npm -v
mkdir student-crud
cd student-crud

Things you need

ItemPurposeCheck
Node.js 20.19 or later (includes npm)Runs the servernode -v
MongoDB ServerStores the dataCompass connects
MongoDB CompassViews the dataOpens
VS Code or another editorEdits the filesOpens
BrowserUses the appOpens
Internet for the first installDownloads packagesnpm 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.

package.json
{
  "name": "student-crud",
  "version": "1.0.0",
  "main": "server.js",
  "scripts": { "start": "node server.js" },
  "dependencies": {
    "express": "^5.1.0",
    "mongoose": "^9.0.0"
  }
}
server.js
// 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) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[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

Terminal
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.

EntryMeaning
name, versionProject name and version
mainMain code file
scripts → startnpm start runs node server.js
dependenciesPackages that npm install downloads
expressWeb server and routes
mongooseConnects to MongoDB
^5.1.05.1.0 or a newer 5.x release

Shortcut: let npm create package.json

Create server.js yourself, then run:

Terminal
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.

  1. Open Compass and click Add new connection.
  2. Enter the address below and click Connect.
Terminal
mongodb://127.0.0.1:27017
PartMeaning
mongodb://MongoDB protocol
127.0.0.1Your own computer
27017Default 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.

Terminal
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:

Terminal
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?

SituationRun npm install?
First setup of the folderYes
Running the app againNo, only npm start
After editing server.jsNo, press Ctrl + C, then npm start
node_modules deleted or not copiedYes
New package added to package.jsonYes

Step 4: Perform the CRUD operations

OperationWhat to doRouteMongoose method
CreateClick + Add Student, fill the form, click SaveGET /students/new
POST /students
create()
ReadOpen the home page, or search by nameGET /
GET /?q=name
find().sort()
UpdateClick Edit, change values, click SaveGET /students/:id/edit
POST /students/:id
findById()
findByIdAndUpdate()
DeleteClick Delete and confirmPOST /students/:id/deletefindByIdAndDelete()

Verify in the database using the MongoDB shell:

Terminal
mongosh
use labdb
db.students.find()

How the code works

The browser never talks to MongoDB directly: Browser ↔ Node and Express ↔ MongoDB.

Terminal
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
});
  1. The browser requests the Add form.
  2. You click Save, which sends a POST request.
  3. express.urlencoded() fills req.body.
  4. Student.create() validates and saves.
  5. On success the server redirects to the list, which fetches the data again. On failure the form returns with errors.
CodeMeaning
req.params.idValue from the URL path
req.query.qValue after ? in the URL
req.bodySubmitted form data
res.send() / res.redirect()Send a page / go to another URL
200, 302, 400, 404, 500Success, 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

FieldRuleSample invalid input
Roll NoRequired, 3 to 10 letters or digits, unique1, or a repeated number
NameRequired, 2 to 40 letters, spaces or dotsA1
EmailRequired, valid formatasha@
DepartmentRequired, chosen from the listNothing selected
MarksRequired, 0 to 100150

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

ConceptMeaning
Client and serverThe browser sends requests; the Node program responds.
GET and POSTGET fetches a page; POST submits data that changes something.
Express routeA function that runs for a given method and URL.
MiddlewareCode that processes a request; express.urlencoded() fills req.body.
Schema and modelThe schema defines fields and rules; the model queries the collection.
Document and collectionSimilar to a row and a table in SQL.
async / awaitWaits for a database result without blocking other requests.
Server-side renderingThe server builds the HTML using template literals.
Post/Redirect/GetRedirecting after saving prevents resubmission on refresh.
XSS protectionesc() 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

ProblemFix
MongoDB connection failed (ECONNREFUSED)Start the MongoDB service.
Cannot find module 'express'Run npm install in the project folder.
EADDRINUSE: port 3000Stop the other program or set a different PORT.
npm is not recognizedInstall Node.js and reopen the terminal.
Duplicate roll numbers are acceptedRemove existing duplicates, then restart so the unique index can be built.

More fixes

ProblemFix
VS Code says running scripts is disabledUse npm.cmd install and npm.cmd start.
File saved as server.js.txtRename it so it ends in .js (or .json).
No MongoDB service on WindowsOpen services.msc and look for MongoDB Server. If absent, run mongod.exe as below, or install MongoDB Community Server.
npm install fails with no internetInstall beforehand and copy the whole folder, if your test rules allow it.
Terminal
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