Week-3:
ExpressJS – Database, RESTful APIs
a. Write a program to connect MongoDB database using Mangoose and perform
CRUD operations.
Step1: Install MongoDB Compass (the GUI tool for MongoDB).
Step2: Create a folder CRUD_Operations
Step3: Install required packages:
npm init -y
npm install express mongoose body-parser
npm i nodemon
Step4:
[Link]
// Import required modules
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const app = express();
[Link]([Link]());
// 1. Connect to MongoDB
mongoose
.connect("mongodb://localhost:27017/mydb", { useNewUrlParser: true,
useUnifiedTopology: true })
.then(() => [Link]("✅ Connected to MongoDB"))
.catch((err) => [Link]("❌ MongoDB connection error:", err));
// 2. Define a Schema & Model
const userSchema = new [Link]({
name: String,
email: String,
age: Number
});
const User = [Link]("User", userSchema);
// ---------------- CRUD OPERATIONS ----------------
// Create (POST)
[Link]("/users", async (req, res) => {
try {
const user = new User([Link]);
await [Link]();
[Link](201).send(user);
} catch (error) {
[Link](400).send(error);
});
// Read All (GET)
[Link]("/users", async (req, res) => {
try {
const users = await [Link]();
[Link](users);
} catch (error) {
[Link](500).send(error);
});
// Read One by ID (GET)
[Link]("/users/:id", async (req, res) => {
try {
const user = await [Link]([Link]);
if (!user) return [Link](404).send({ message: "User not found" });
[Link](user);
} catch (error) {
[Link](500).send(error);
});
// Update (PUT)
[Link]("/users/:id", async (req, res) => {
try {
const user = await [Link]([Link], [Link], { new: true });
if (!user) return [Link](404).send({ message: "User not found" });
[Link](user);
} catch (error) {
[Link](400).send(error);
});
// Delete (DELETE)
[Link]("/users/:id", async (req, res) => {
try {
const user = await [Link]([Link]);
if (!user) return [Link](404).send({ message: "User not found" });
[Link]({ message: "User deleted successfully" });
} catch (error) {
[Link](500).send(error);
}
});
// --------------------------------------------------
// Start server
const PORT = 3000;
[Link](PORT, () => [Link](`🚀 Server running at [Link]
Output:
b. Write a program to develop a single page application using RESTful APIs.
REST = Representational State Transfer
It is a set of rules/standards for building web services.
A REST API allows a client (frontend) to communicate with a server (backend) using
HTTP methods.
A SPA is a web app that loads only one HTML page initially.
After that, it updates the page dynamically without reloading the entire page.
It communicates with the backend through REST APIs
[Link]:
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cors = require("cors");
[Link]([Link]());
[Link](cors()); // allow frontend to call backend
// Temporary data in-memory
let users = [
{ id: 1, name: "John Doe" },
{ id: 2, name: "Jane Smith" }
];
// GET all users
[Link]("/api/users", (req, res) => {
[Link](users);
});
// POST add user
[Link]("/api/users", (req, res) => {
const newUser = { id: [Link] + 1, name: [Link] };
[Link](newUser);
[Link](newUser);
});
// DELETE user by ID
[Link]("/api/users/:id", (req, res) => {
users = [Link](u => [Link] !== parseInt([Link]));
[Link]({ message: "User deleted" });
});
// Start server
[Link](3000, () => [Link]("🚀 Server running at [Link]
[Link]:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple SPA with REST API</title>
</head>
<body>
<h1>User Management (SPA)</h1>
<!-- Display Users -->
<div id="userList"></div>
<!-- Add User -->
<input type="text" id="username" placeholder="Enter name">
<button onclick="addUser()">Add User</button>
<script>
const API_URL = "[Link]
// Load all users
async function loadUsers() {
const res = await fetch(API_URL);
const users = await [Link]();
const list = [Link]("userList");
[Link] = "";
[Link](user => {
[Link] += `<p>${[Link]}
<button onclick="deleteUser(${[Link]})">Delete</button></p>`;
});
// Add user
async function addUser() {
const name = [Link]("username").value;
await fetch(API_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: [Link]({ name })
});
[Link]("username").value = "";
loadUsers();
// Delete user
async function deleteUser(id) {
await fetch(`${API_URL}/${id}`, { method: "DELETE" });
loadUsers();
// Load users on page load
loadUsers();
</script>
</body>
</html>
Execution:
D:\2025-26\SEM-1\MERN\test\my_spa_proj\backend> node [Link]
🚀 Server running at [Link]
Open the [Link] with Live Server
Output: