0% found this document useful (0 votes)
8 views9 pages

Express.js CRUD API with MongoDB Guide

This document provides a step-by-step guide to set up an Express.js application with MongoDB for creating a RESTful API. It includes instructions for project structure, environment variable configuration, server setup, and CRUD operations for user management. Additionally, it outlines how to create a simple single-page application (SPA) to interact with the API using HTML and JavaScript.

Uploaded by

Sandhya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views9 pages

Express.js CRUD API with MongoDB Guide

This document provides a step-by-step guide to set up an Express.js application with MongoDB for creating a RESTful API. It includes instructions for project structure, environment variable configuration, server setup, and CRUD operations for user management. Additionally, it outlines how to create a simple single-page application (SPA) to interact with the API using HTML and JavaScript.

Uploaded by

Sandhya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

4.

Express JS – Database, RESTful APIs

Step-by-Step Guide: [Link] + MongoDB + RESTful


API
🧱 1. Setup Your Project
mkdir express-api
cd express-api
npm init -y
npm install express mongoose dotenv

📁 2. Project Structure
express-api/

├── models/
│ └── [Link]

├── routes/
│ └── [Link]

├── .env
├── [Link]
└── [Link]

📄 3. .env – Store environment variables


PORT=3000
MONGODB_URI=mongodb://localhost:27017/expressapi

⚙️4. [Link] – Entry point


const app = require('./app');
const mongoose = require('mongoose');
require('dotenv').config();

const PORT = [Link] || 3000;

[Link]([Link].MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
[Link]('Connected to MongoDB');
[Link](PORT, () => [Link](`Server running on port ${PORT}`));
}).catch(err => [Link]('MongoDB connection error:', err));

🚀 5. [Link] – Initialize Express App


const express = require('express');
const userRoutes = require('./routes/[Link]');
const app = express();

[Link]([Link]()); // Body parser


[Link]('/api/users', userRoutes); // Register routes

[Link] = app;

👤 6. models/[Link]
const mongoose = require('mongoose');

const UserSchema = new [Link]({


name: { type: String, required: true },
email: { type: String, required: true, unique: true }
}, { timestamps: true });

[Link] = [Link]('User', UserSchema);

📦 7. routes/[Link]
const express = require('express');
const router = [Link]();
const User = require('../models/[Link]');

// CREATE
[Link]('/', async (req, res) => {
try {
const user = await [Link]([Link]);
[Link](201).json(user);
} catch (err) {
[Link](400).json({ error: [Link] });
}
});

// READ ALL
[Link]('/', async (req, res) => {
try {
const users = await [Link]();
[Link](users);
} catch (err) {
[Link](500).json({ error: [Link] });
}
});

// READ ONE
[Link]('/:id', async (req, res) => {
try {
const user = await [Link]([Link]);
if (!user) return [Link](404).json({ error: 'User not
found' });
[Link](user);
} catch (err) {
[Link](500).json({ error: [Link] });
}
});
// UPDATE
[Link]('/:id', async (req, res) => {
try {
const user = await [Link]([Link], [Link],
{ new: true });
if (!user) return [Link](404).json({ error: 'User not
found' });
[Link](user);
} catch (err) {
[Link](400).json({ error: [Link] });
}
});

// DELETE
[Link]('/:id', async (req, res) => {
try {
const user = await [Link]([Link]);
if (!user) return [Link](404).json({ error: 'User not
found' });
[Link]({ message: 'User deleted' });
} catch (err) {
[Link](500).json({ error: [Link] });
}
});

[Link] = router;

✅ 8. Run Your API


node [Link]

You can now test endpoints like:

Method URL Description


POST /api/users Create a user
GET /api/users List all users
GET /api/users/:id Get one user
PUT /api/users/:id Update a user
DELETE /api/users/:id Delete a user
4 a) Write a program to connect MongoDB database using Mangoose and perform CRUD
models/[Link] – Mongoose Schema
const mongoose = require('mongoose');

const UserSchema = new [Link]({


name: { type: String, required: true },
email: { type: String, required: true, unique: true },
age: { type: Number }
}, { timestamps: true });

[Link] = [Link]('User', UserSchema);

[Link] – Main Application with CRUD


const express = require('express');
const mongoose = require('mongoose');
require('dotenv').config();

const User = require('./models/[Link]');

const app = express();


[Link]([Link]());

// Connect to MongoDB
[Link]([Link].MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => [Link]('✅ Connected to MongoDB'))
.catch(err => [Link]('❌ MongoDB connection error:', err));

// =======================
// CRUD ROUTES
// =======================

// Create a new user


[Link]('/users', async (req, res) => {
try {
const user = await [Link]([Link]);
[Link](201).json(user);
} catch (err) {
[Link](400).json({ error: [Link] });
}
});

// Get all users


[Link]('/users', async (req, res) => {
try {
const users = await [Link]();
[Link](users);
} catch (err) {
[Link](500).json({ error: [Link] });
}
});

// Get a single user by ID


[Link]('/users/:id', async (req, res) => {
try {
const user = await [Link]([Link]);
if (!user) return [Link](404).json({ error: 'User not
found' });
[Link](user);
} catch (err) {
[Link](500).json({ error: [Link] });
}
});

// Update a user by ID
[Link]('/users/:id', async (req, res) => {
try {
const user = await [Link]([Link], [Link],
{ new: true });
if (!user) return [Link](404).json({ error: 'User not
found' });
[Link](user);
} catch (err) {
[Link](400).json({ error: [Link] });
}
});

// Delete a user by ID
[Link]('/users/:id', async (req, res) => {
try {
const user = await [Link]([Link]);
if (!user) return [Link](404).json({ error: 'User not
found' });
[Link]({ message: 'User deleted successfully' });
} catch (err) {
[Link](500).json({ error: [Link] });
}
});

// =======================

const PORT = [Link] || 3000;


[Link](PORT, () => {
[Link](`🚀 Server running at [Link]
});

b) Write a program to develop a single page application using RESTful APIs

backend/models/[Link]

const mongoose = require('mongoose');

const UserSchema = new [Link]({


name: String,
email: String
}, { timestamps: true });

[Link] = [Link]('User', UserSchema);


backend/[Link]

const express = require('express');


const mongoose = require('mongoose');
const User = require('./models/[Link]');
const cors = require('cors');
require('dotenv').config();

const app = express();


[Link](cors());
[Link]([Link]());

// MongoDB connection
[Link]([Link].MONGODB_URI)
.then(() => [Link]('MongoDB Connected'))
.catch(err => [Link](err));

// RESTful API Endpoints

// Get all users


[Link]('/api/users', async (req, res) => {
const users = await [Link]();
[Link](users);
});

// Create new user


[Link]('/api/users', async (req, res) => {
const user = await [Link]([Link]);
[Link](201).json(user);
});

// Update user
[Link]('/api/users/:id', async (req, res) => {
const user = await [Link]([Link], [Link], { new:
true });
[Link](user);
});

// Delete user
[Link]('/api/users/:id', async (req, res) => {
await [Link]([Link]);
[Link]({ message: 'User deleted' });
});

const PORT = [Link] || 3000;


[Link](PORT, () => [Link](`Server running on [Link]
{PORT}`));

🌐 2. Frontend (HTML + JavaScript SPA)


➤ frontend/[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SPA – User Management</title>
<style>
body { font-family: Arial; max-width: 600px; margin: 20px auto; }
input { margin: 5px; }
button { margin: 5px; }
</style>
</head>
<body>

<h1>User Management SPA</h1>

<form id="userForm">
<input type="text" id="name" placeholder="Name" required />
<input type="email" id="email" placeholder="Email" required />
<input type="hidden" id="userId" />
<button type="submit">Save User</button>
</form>

<ul id="userList"></ul>

<script>
const apiUrl = '[Link]

async function fetchUsers() {


const res = await fetch(apiUrl);
const users = await [Link]();
const userList = [Link]('userList');
[Link] = '';
[Link](user => {
const li = [Link]('li');
[Link] = `
<strong>${[Link]}</strong> (${[Link]})
<button onclick="editUser('${user._id}', '${[Link]}', '$
{[Link]}')">Edit</button>
<button onclick="deleteUser('${user._id}')">Delete</button>
`;
[Link](li);
});
}

async function createOrUpdateUser(event) {


[Link]();
const name = [Link]('name').value;
const email = [Link]('email').value;
const userId = [Link]('userId').value;

const method = userId ? 'PUT' : 'POST';


const url = userId ? `${apiUrl}/${userId}` : apiUrl;

await fetch(url, {
method: method,
headers: { 'Content-Type': 'application/json' },
body: [Link]({ name, email })
});

[Link]('userForm').reset();
fetchUsers();
}

async function deleteUser(id) {


await fetch(`${apiUrl}/${id}`, { method: 'DELETE' });
fetchUsers();
}
function editUser(id, name, email) {
[Link]('userId').value = id;
[Link]('name').value = name;
[Link]('email').value = email;
}

[Link]('userForm').addEventListener('submit',
createOrUpdateUser);
fetchUsers();
</script>
</body>
</html>

Run Backend
cd backend
npm install
node [Link]

3. Open Frontend

Just open the frontend/[Link] in your browser (no server needed).

If you want to serve the frontend via Express as well, I can show you how to move the
HTML file into public/ and serve it from Express.

Output

MongoDB Connected
Server running on [Link]
Initial Page (No users yet)
User Management SPA
[ Name ] [ Email ] [ Save User ]

<user list appears here, initially empty>

➕ When you enter a user:

Example Input:

Name: Alice
Email: alice@[Link]
[ Save User ]

After clicking Save:


User Management SPA
[ Name ] [ Email ] [ Save User ]

- Alice (alice@[Link]) [Edit] [Delete]

✏️After clicking [Edit]

The form at the top fills with the user data:

Name: Alice
Email: alice@[Link]
[ Save User ] (updates instead of creating)

❌ After clicking [Delete]

The user is removed from the list, and the display updates instantly:

(no users)

You might also like