Skip to main content

Command Palette

Search for a command to run...

πŸš† Mini Project: Railway Ticket Booking System

Published
β€’5 min read
P
Hi there, tech enthusiasts! I'm a passionate Software Developer driven by a love for continuous learning and innovation. I thrive on exploring new tools and technologies, pushing boundaries, and finding creative solutions to complex problems. What You'll Find Here On my Hashnode blog, I share: πŸš€ In-depth explorations of emerging technologies πŸ’‘ Practical tutorials and how-to guides πŸ”§Insights on software development best practices πŸš€Reviews of the latest tools and frameworks πŸ’‘ Personal experiences from real-world projects. Join me as we bridge imagination and implementation in the tech world. Whether you're a seasoned pro or just starting out, there's always something new to discover! Let’s connect and grow together! 🌟

πŸ“Œ Features Covered

  • Create railway bookings

  • View bookings in browser

  • Filter by source & destination

  • Sort by journey date

  • Pagination (page-wise data)

  • Strong backend validations

  • Proper frontend ↔ backend connectivity


πŸ“ Folder Structure (IMPORTANT)

railway-booking-app/
β”‚
β”œβ”€β”€ backend/
β”‚   β”œβ”€β”€ config/
β”‚   β”‚   └── db.js
β”‚   β”‚
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   └── Booking.js
β”‚   β”‚
β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   └── bookingRoutes.js
β”‚   β”‚
β”‚   β”œβ”€β”€ middlewares/
β”‚   β”‚   └── errorHandler.js
β”‚   β”‚
β”‚   β”œβ”€β”€ app.js
β”‚   └── server.js
β”‚
β”œβ”€β”€ frontend/
β”‚   β”œβ”€β”€ index.html
β”‚   β”œβ”€β”€ style.css
β”‚   └── script.js
β”‚
β”œβ”€β”€ package.json
└── .env

πŸ”§ Backend Code (Node + Express + MongoDB)


1️⃣ package.json

{
  "name": "railway-booking-app",
  "version": "1.0.0",
  "description": "Railway Booking Mini Project",
  "main": "backend/server.js",
  "scripts": {
    "start": "node backend/server.js",
    "dev": "nodemon backend/server.js"
  },
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^16.4.5",
    "express": "^4.19.2",
    "mongoose": "^8.6.1"
  }
}

2️⃣ .env

PORT=5000
MONGO_URI=mongodb://127.0.0.1:27017/railwayDB

3️⃣ backend/config/db.js

const mongoose = require("mongoose");

const connectDB = async () => {
  try {
    await mongoose.connect(process.env.MONGO_URI);
    console.log("MongoDB Connected");
  } catch (error) {
    console.error("DB Error:", error.message);
    process.exit(1);
  }
};

module.exports = connectDB;

4️⃣ backend/models/Booking.js

πŸ‘‰ Day 27: Validations + Custom Validation

const mongoose = require("mongoose");

const bookingSchema = new mongoose.Schema(
  {
    passengerName: {
      type: String,
      required: true,
      minlength: 3
    },
    age: {
      type: Number,
      required: true,
      min: 5
    },
    source: {
      type: String,
      required: true
    },
    destination: {
      type: String,
      required: true
    },
    journeyDate: {
      type: Date,
      required: true,
      validate: {
        validator: function (value) {
          return value > new Date();
        },
        message: "Journey date must be in the future"
      }
    },
    trainNumber: {
      type: String,
      required: true
    }
  },
  { timestamps: true }
);

module.exports = mongoose.model("Booking", bookingSchema);

5️⃣ backend/routes/bookingRoutes.js

πŸ‘‰ Day 26: Filtering, Sorting, Pagination

const express = require("express");
const Booking = require("../models/Booking");

const router = express.Router();

// CREATE booking
router.post("/", async (req, res, next) => {
  try {
    const booking = await Booking.create(req.body);
    res.status(201).json(booking);
  } catch (error) {
    next(error);
  }
});

// GET bookings (filter + sort + pagination)
router.get("/", async (req, res, next) => {
  try {
    const { source, destination, page = 1 } = req.query;

    const filter = {};
    if (source) filter.source = source;
    if (destination) filter.destination = destination;

    const limit = 5;
    const skip = (page - 1) * limit;

    const bookings = await Booking.find(filter)
      .sort({ journeyDate: 1 })
      .skip(skip)
      .limit(limit);

    res.json(bookings);
  } catch (error) {
    next(error);
  }
});

module.exports = router;

6️⃣ backend/middlewares/errorHandler.js

const errorHandler = (err, req, res, next) => {
  res.status(400).json({
    error: err.message
  });
};

module.exports = errorHandler;

7️⃣ backend/app.js

const express = require("express");
const cors = require("cors");
const bookingRoutes = require("./routes/bookingRoutes");
const errorHandler = require("./middlewares/errorHandler");

const app = express();

app.use(cors());
app.use(express.json());

app.use("/api/bookings", bookingRoutes);
app.use(errorHandler);

module.exports = app;

8️⃣ backend/server.js

require("dotenv").config();
const app = require("./app");
const connectDB = require("./config/db");

connectDB();

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

🎨 Frontend Code (HTML + CSS + JS)


9️⃣ frontend/index.html

<!DOCTYPE html>
<html>
<head>
  <title>Railway Booking</title>
  <link rel="stylesheet" href="style.css" />
</head>
<body>

<h2>Railway Ticket Booking</h2>

<form id="bookingForm">
  <input type="text" placeholder="Passenger Name" id="name" required />
  <input type="number" placeholder="Age" id="age" required />
  <input type="text" placeholder="Source" id="source" required />
  <input type="text" placeholder="Destination" id="destination" required />
  <input type="date" id="date" required />
  <input type="text" placeholder="Train Number" id="train" required />
  <button type="submit">Book Ticket</button>
</form>

<h3>Bookings</h3>
<div id="bookings"></div>

<script src="script.js"></script>
</body>
</html>

πŸ”Ÿ frontend/style.css

body {
  font-family: Arial;
  background: #f4f6f8;
  padding: 20px;
}

form input, button {
  display: block;
  margin: 8px 0;
  padding: 8px;
}

button {
  background: #007bff;
  color: white;
  border: none;
}

.booking {
  background: white;
  padding: 10px;
  margin-top: 10px;
  border-radius: 4px;
}

1️⃣1️⃣ frontend/script.js

const API = "http://localhost:5000/api/bookings";

const form = document.getElementById("bookingForm");
const bookingsDiv = document.getElementById("bookings");

form.addEventListener("submit", async (e) => {
  e.preventDefault();

  const data = {
    passengerName: name.value,
    age: age.value,
    source: source.value,
    destination: destination.value,
    journeyDate: date.value,
    trainNumber: train.value
  };

  await fetch(API, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(data)
  });

  loadBookings();
  form.reset();
});

async function loadBookings() {
  const res = await fetch(API);
  const bookings = await res.json();

  bookingsDiv.innerHTML = "";
  bookings.forEach(b => {
    bookingsDiv.innerHTML += `
      <div class="booking">
        <b>${b.passengerName}</b> | ${b.source} β†’ ${b.destination}<br/>
        Train: ${b.trainNumber} | Date: ${new Date(b.journeyDate).toDateString()}
      </div>
    `;
  });
}

loadBookings();

🎯 Concepts Covered (Mapping with Day 26 & 27)

ConceptWhere Used
Filteringsource, destination query
Sorting.sort({ journeyDate: 1 })
Paginationskip() + limit()
ValidationSchema rules
Custom ValidationFuture journey date
Frontend UIHTML/CSS/JS
API Connectivityfetch()

🧠 Student Tasks (VERY IMPORTANT)

1️⃣ Add filter dropdown for source & destination
2️⃣ Add page buttons (Next / Prev)
3️⃣ Show validation error messages on UI
4️⃣ Add delete booking feature
5️⃣ Add total bookings count


πŸ”” Stay Connected

If you found this article helpful and want to receive more such beginner-friendly and industry-relevant Node JS notes, tutorials, and project ideas β€” πŸ“© Subscribe to our newsletter by entering your email below.

And if you're someone who wants to prepare for tech interviews while having a little fun and entertainment, πŸŽ₯ Don’t forget to subscribe to my YouTube channel – Knowledge Factory 22 – for regular content on tech concepts, career tips, and coding insights!

Stay curious. Keep building. πŸš€

More from this blog

T

Technologies: Tools & Tips | Expert Guides on Latest Tech Tools

125 posts

Railway Ticket Booking System Project