Mohit Decodes
169 subscribers
68 photos
1 video
1 file
200 links
✨ Source Code for All Projects – Download & practice easily
πŸŽ“ Free Tutorials & Notes
πŸ› οΈ Coding Projects & Mini Apps
πŸ“Œ Subscribe on YouTube: Mohit Decodes πŸ””
πŸ“© For business inquiries: @MohitChoudhary0007
Download Telegram
*πŸ—„οΈ Database Integration β€” MongoDB with Node.js*

Now you move from temporary data (arrays) β†’ real database storage.

Backend apps must store data permanently.

That's where databases come in.

*🧠 What is a Database*

A database stores data persistently.

*Examples:*
- E-commerce: Products, orders
- Social media: Users, posts
- Banking app: Transactions

*Without database β†’ data disappears when server restarts.*

*πŸƒ What is MongoDB*

MongoDB is a NoSQL database.

*Instead of tables β†’ it stores documents (JSON-like data).*

*Example document:*
{
"name": "Deepak",
"role": "Developer",
"age": 25
}

*Collection = group of documents*
*Database = group of collections*

*πŸ“¦ Why MongoDB is Popular*

βœ… *JSON-like data*
βœ… *Flexible schema*
βœ… *Works perfectly with JavaScript*
βœ… *Scales easily*

*Common in MERN stack.*

*MERN = MongoDB + Express + React + Node*

*πŸ”— Connecting MongoDB with Node.js*

We use a library called Mongoose.

*Install:*
npm install mongoose

*⚑ Step 1 β€” Connect Database*

*Example:*
const mongoose = require("mongoose");

mongoose.connect("mongodb://127.0.0.1:27017/myapp")
.then(() => console.log("MongoDB Connected"))
.catch(err => console.log(err));

*Now Node server is connected to MongoDB.*

*🧩 Step 2 β€” Create Schema*

*Schema defines data structure.*

*Example:*
const userSchema = new mongoose.Schema({
name: String,
age: Number
});

*πŸ“„ Step 3 β€” Create Model*

*Model allows database operations.*
const User = mongoose.model("User", userSchema);

*βž• Step 4 β€” Create Data*
app.post("/users", async (req, res) => {
const user = new User({
name: req.body.name,
age: req.body.age
});

await user.save();
res.json(user);
});

*πŸ” Step 5 β€” Fetch Data*
app.get("/users", async (req, res) => {
const users = await User.find();
res.json(users);
});

*❌ Step 6 β€” Delete Data*
app.delete("/users/:id", async (req, res) => {
await User.findByIdAndDelete(req.params.id);
res.json({ message: "User deleted" });
});

*✏️ Step 7 β€” Update Data*
app.put("/users/:id", async (req, res) => {
const user = await User.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true }
);
res.json(user);
});

*πŸ”„ Full Backend Flow Now*

*React β†’ API request*
*Express β†’ Handles route*
*Mongoose β†’ Talks to MongoDB*
*MongoDB β†’ Stores data*

*⚠️ Common Beginner Mistakes*

- *Forgetting to install mongoose*
- *Not using async/await*
- *Wrong MongoDB URL*
- *Not validating schema*

*πŸ§ͺ Mini Practice Task*

*Build Product API with MongoDB*

*Routes:*
- POST /products
- GET /products
- PUT /products/:id
- DELETE /products/:id

*Fields:*
name
price
category

βœ… *Mini Practice Task – Solution*

This solution implements:

βœ” POST /products β†’ Add product
βœ” GET /products β†’ Fetch products
βœ” PUT /products/:id β†’ Update product
βœ” DELETE /products/:id β†’ Delete product

🟒 *Step 1 β€” Install Required Packages*

npm init -y
npm install express mongoose cors


πŸ“„ *Step 2 β€” Create server.js*

const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");

const app = express();

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

/* ---------------- DATABASE CONNECTION ---------------- */

mongoose.connect("mongodb://127.0.0.1:27017/productdb")
.then(() => console.log("MongoDB connected"))
.catch(err => console.log(err));

/* ---------------- PRODUCT SCHEMA ---------------- */

const productSchema = new mongoose.Schema({
name: String,
price: Number,
category: String
});

const Product = mongoose.model("Product", productSchema);

/* ---------------- ROUTES ---------------- */

/* CREATE PRODUCT */
app.post("/products", async (req, res) => {

const product = new Product({
name: req.body.name,
price: req.body.price,
category: req.body.category
});

await product.save();

res.json(product);
});

/* GET PRODUCTS */
app.get("/products", async (req, res) => {

const products = await Product.find();

res.json(products);
});

/* UPDATE PRODUCT */
app.put("/products/:id", async (req, res) => {

const product = await Product.
findByIdAndUpdate(
req.params.id,
req.body,
{ new: true }
);

res.json(product);
});

/* DELETE PRODUCT */
app.delete("/products/:id", async (req, res) => {

await Product.findByIdAndDelete(req.params.id);

res.json({ message: "Product deleted" });
});

/* ---------------- START SERVER ---------------- */

app.listen(3000, () => {
console.log("Server running on port 3000");
});


▢️ *Step 3 β€” Run Server*

node server.js

You should see:

MongoDB connected
Server running on port 3000


🌐 *Step 4 β€” Test API*

Using Postman / Thunder Client


βž• *Add Product*

POST

http://localhost:3000/products

Body:

{
"name": "Laptop",
"price": 800,
"category": "Electronics"
}


πŸ“₯ *Get Products*

GET

http://localhost:3000/products

✏️ *Update Product*

PUT

http://localhost:3000/products/:id

Body:

{
"price": 900
}

❌ *Delete Product*

DELETE

http://localhost:3000/products/:id

🧠 *What You Learned*

βœ” Connecting MongoDB with Node.js
βœ” Creating schema & model
βœ” Creating CRUD API
βœ” Using async/await with database
βœ” REST API with database storage

*➑️ Double Tap β™₯️ For More*
❀1
Employee Management System in Angular 21 | Full Project
https://youtu.be/1clW93zDs20
πŸ‘2
*πŸš€ MERN Stack Architecture (End-to-End Flow)*

Now you connect everything you learned into one complete system.

πŸ‘‰ MERN = MongoDB + Express + React + Node.js

This is the most popular full stack architecture.


*🧠 What is MERN Stack*

A full stack system where:
- React β†’ Frontend (UI)
- Node + Express β†’ Backend (API)
- MongoDB β†’ Database

All using JavaScript πŸ”₯
 

*πŸ”„ Complete MERN Flow (Very Important)*

1️⃣ User interacts with UI (React)
2️⃣ React sends API request
3️⃣ Express receives request
4️⃣ Backend processes logic
5️⃣ Mongoose interacts with MongoDB
6️⃣ Database returns data
7️⃣ Backend sends JSON response
8️⃣ React updates UI
πŸ‘‰ This is the core interview explanation.
 

*🧩 Architecture Diagram (Simple)*
React (Frontend)
↓
API Request (fetch/axios)
↓
Node + Express (Backend)
↓
Mongoose
↓ MongoDB (Database) ↑
JSON Response
↑
React UI Updates

 

*πŸ“ Real MERN Project Structure*
project/
β”œβ”€β”€ client/ (React App)
β”‚ └── src/
β”‚ β”œβ”€β”€ components/
β”‚ β”œβ”€β”€ pages/
β”‚ └── App.js
β”‚ β”œβ”€β”€ server/ (Backend)
β”‚ β”œβ”€β”€ models/
β”‚ β”œβ”€β”€ routes/
β”‚ β”œβ”€β”€ controllers/
β”‚ └── server.js
β”‚ β”œβ”€β”€ package.json

 

*πŸ“¦ Frontend Responsibilities (React)*
- UI rendering
- API calls
- State management
- Form handling

Example: fetch("/api/users")
 

*βš™οΈ Backend Responsibilities (Node + Express)*
- API creation
- Business logic
- Authentication
- Database interaction

Example: app.get("/users", ...)

 
*πŸ—„οΈ Database Responsibilities (MongoDB)*
- Store data
- Retrieve data
- Update/Delete data

Example: User.find()

 

*πŸ” Where Authentication Fits*

Flow: React β†’ Login β†’ Backend

Backend β†’ Verify β†’ Generate JWT

Frontend stores token
Frontend sends token in future requests


*⚠️ Common Beginner Mistakes*

- Mixing frontend and backend code
- Not handling errors
- No folder structure
- Not using environment variables 

*πŸ§ͺ Mini Practice Task*

Design a MERN app:

πŸ‘‰ Features to build:
- User signup/login
- Add products
- View products
- Delete products

πŸ‘‰ Think:
- What goes in frontend?
- What goes in backend?
- What goes in database?

*πŸ§ͺ Mini Task Solution: Try it yourself first*
 

*🧩 1. FRONTEND (React) – What goes here?*

πŸ‘‰ Responsibility: UI + API calls + state

πŸ“ Structure
client/src/
β”œβ”€β”€ pages/
β”‚ β”œβ”€β”€ Login.js
β”‚ β”œβ”€β”€ Signup.js
β”‚ β”œβ”€β”€ Dashboard.js
β”œβ”€β”€ components/
β”‚ β”œβ”€β”€ ProductForm.js
β”‚ β”œβ”€β”€ ProductList.js
β”œβ”€β”€ services/
β”‚ └── api.js

βš™οΈ What it does:
- Login/Signup forms
- Store JWT (localStorage)
- Call APIs
- Display products

🧠 Example API Calls:
// Login
fetch("/api/auth/login", {
method: "POST",
body: JSON.stringify({ email, password }),
});

// Get Products
fetch("/api/products", {
headers: {
Authorization: Bearer ${token}
}
});

 

*βš™οΈ 2. BACKEND (Node + Express) – What goes here?*

πŸ‘‰ Responsibility: Logic + API + Auth

πŸ“ Structure
server/
β”œβ”€β”€ models/
β”‚ β”œβ”€β”€ User.js
β”‚ β”œβ”€β”€ Product.js
β”œβ”€β”€ controllers/
β”‚ β”œβ”€β”€ authController.js
β”‚ β”œβ”€β”€ productController.js
β”œβ”€β”€ routes/
β”‚ β”œβ”€β”€ authRoutes.js
β”‚ β”œβ”€β”€ productRoutes.js
β”œβ”€β”€ middleware/
β”‚ └── authMiddleware.js
└── server.js

 
*πŸ”‘ APIs You’ll Build*

πŸ” Auth APIs
POST /api/auth/signup
POST /api/auth/login

πŸ“¦ Product APIs
GET /api/products
POST /api/products
DELETE /api/products/:id

 
*🧠 Example Controller Logic*
// Get Products
exports.getProducts = async (req, res) => {
const products = await Product.find({ user: req.user.id });
res.json(products);
};
 

*πŸ” Authentication Flow*
1. User logs in
2. Backend verifies user
3. Backend sends JWT
4. React stores token
5. Token sent in headers for protected routes
Authorization: Bearer <token>
 

*πŸ—„οΈ 3. DATABASE (MongoDB) – What goes here?*
πŸ‘‰ Responsibility: Store & manage data
 

*πŸ‘€ User Schema*
{
name: String,
email: String,
password: String
}

 
*πŸ“¦ Product Schema*
{
name: String,
price: Number,
user: ObjectId // reference to user
}

 
*πŸ”„ Complete Flow (End-to-End)*

πŸ‘‰ Example: User adds a product
1. React form submit
2. API call β†’ POST /api/products
3. Express route receives request
4. Auth middleware verifies JWT
5. Controller saves product in MongoDB
6. Response sent back
7. React updates UI

 
*πŸš€ Interview Tip:*
πŸ‘‰ If interviewer asks β€œExplain MERN flow”

You can say:
β€œIn a MERN app, the React frontend sends API requests to a Node/Express backend. The backend processes business logic and interacts with MongoDB using Mongoose. Data is returned as JSON, and React updates the UI. Authentication is handled using JWT, which is stored on the client and sent with each protected request.”


*⚠️ Important Things to Mention (Bonus Points)*
- Use .env for secrets (JWT, DB URI)
- Use middleware for authentication
- Keep controllers clean (separation of concerns)
- Handle errors properly (try-catch)

 
*🧠 Quick Mental Map*
πŸ‘‰ Always think like this:
UI β†’ API β†’ Logic β†’ DB β†’ Response β†’ UI


*➑️ Double Tap ❀️ For More*
❀2
DSA #36 - Core Data Structures | HashMap Basics Explained | Key Value
https://youtu.be/aVxXSt90TE4
πŸ‘1