0% found this document useful (0 votes)
2 views32 pages

MERN_Stack_Complete_Guide

The document is a comprehensive guide on the MERN stack, covering MongoDB, Express.js, React, and Node.js, with a focus on their roles in full-stack web development. It includes JavaScript fundamentals, server setup, CRUD operations, and essential interview questions. Additionally, it provides resources for learning and a cheat sheet of commands for practical use in development.

Uploaded by

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

MERN_Stack_Complete_Guide

The document is a comprehensive guide on the MERN stack, covering MongoDB, Express.js, React, and Node.js, with a focus on their roles in full-stack web development. It includes JavaScript fundamentals, server setup, CRUD operations, and essential interview questions. Additionally, it provides resources for learning and a cheat sheet of commands for practical use in development.

Uploaded by

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

MERN Stack

Complete Interview Guide

MongoDB · [Link] · React · [Link] · JavaScript

2-Day Crash Course for Placement Interviews

M MongoDB E Express R React N [Link]

JavaScript is used across ALL 4 layers — one language, full stack.


Table of Contents
1. What is MERN Stack? — The Big Picture
2. JavaScript Fundamentals — Core language — used in all 4 layers
3. [Link] — Running JS on the server
4. [Link] — Building REST APIs
5. MongoDB & Mongoose — Database & schemas
6. React — Building the UI
7. Connecting Frontend + Backend — Full-stack data flow
8. Top Interview Q&A; — 50+ questions with answers
9. Commands Cheat Sheet — All essential commands
10. Platforms to Learn — Best free resources
Chapter 1 — What is MERN Stack?

MERN is a collection of four JavaScript technologies used to build full-stack web applications:

Letter Technology Role Runs Where

M MongoDB Database — stores data Server (cloud/local)

E [Link] Backend framework — API routes Server ([Link])

R React Frontend UI library Browser

N [Link] JS runtime — runs server code Server

The Flow — How They Talk to Each Other:


• 1. User clicks a button in React (browser)
• 2. React sends an HTTP request to Express (fetch/axios)
• 3. Express receives the request, runs logic
• 4. Express queries MongoDB via Mongoose
• 5. MongoDB returns data to Express
• 6. Express sends JSON response back to React
• 7. React updates the UI with the data

■ KEY INSIGHT: JavaScript (JS) is used in ALL layers. React = JS in browser. Express/Node = JS on
server. MongoDB queries via Mongoose = JS. This is why MERN is popular — one language
everywhere.
Chapter 2 — JavaScript Fundamentals

2.1 Variables
var name = 'old'; // avoid — function scoped, can be redeclared
let age = 25; // block scoped, can be changed
const PI = 3.14; // block scoped, cannot be reassigned — prefer this

Interview Q: Difference between var, let, const?


var is function-scoped and can be re-declared. let and const are block-scoped. const cannot be
reassigned (but object properties can be mutated). Use const by default, let when you need to
reassign, avoid var.

2.2 Data Types


Type Example Notes

String 'hello' / "world" Text

Number 42 / 3.14 No int vs float distinction

Boolean true / false Comparison results

Array [1, 2, 3] Ordered list

Object { name: 'Ravi' } Key-value pairs

null null Intentional empty value

undefined undefined Variable declared but not set

2.3 Functions
// Regular function
function add(a, b) { return a + b; }

// Arrow function (ES6) — used everywhere in React


const add = (a, b) => a + b;

// Arrow with body


const greet = (name) => {
const msg = 'Hello ' + name;
return msg;
};

// Default parameter
const greet = (name = 'World') => `Hello ${name}`;

// Rest parameter
const sum = (...nums) => [Link]((a, b) => a + b, 0);

2.4 Arrays — Most Asked in Interviews


const nums = [1, 2, 3, 4, 5];

[Link](n => n * 2) // [2,4,6,8,10] transform each item


[Link](n => n > 2) // [3,4,5] keep matching items
[Link](n => n === 3) // 3 first match
[Link](n => n === 3) // 2 index of first match
[Link]((sum,n)=>sum+n,0) // 15 reduce to single value
[Link](n=>[Link](n))// loops, returns undefined
[Link](n => n > 4) // true any match?
[Link](n => n > 0) // true all match?
[Link](3) // true is value present?
[...nums, 6] // spread — add items
[Link](1,3) // [2,3] extract portion
[Link](1,1) // removes item at index 1
[Link]((a,b) => a - b) // sort ascending

2.5 Objects
const user = { name: 'Ravi', age: 25, city: 'Chennai' };

// Access
[Link]; // 'Ravi'
user['age']; // 25

// Destructuring — used heavily in React


const { name, age } = user;
const { name: fullName } = user; // rename while destructuring

// Spread operator
const updated = { ...user, city: 'Mumbai' };

// Shorthand property
const name = 'Ravi';
const obj = { name }; // same as { name: name }

// Optional chaining (avoids 'cannot read property of undefined')


user?.address?.street; // undefined instead of error

// Nullish coalescing
const name = [Link] ?? 'Anonymous';

2.6 Async / Await & Promises


This is critical for MERN — every API call is async.

// Promise
fetch('/api/users')
.then(res => [Link]())
.then(data => [Link](data))
.catch(err => [Link](err));

// Async/Await (cleaner — use this)


const getUsers = async () => {
try {
const res = await fetch('/api/users');
const data = await [Link]();
[Link](data);
} catch (err) {
[Link](err);
}
};

// [Link] — run multiple async ops in parallel


const [users, posts] = await [Link]([
fetch('/api/users').then(r=>[Link]()),
fetch('/api/posts').then(r=>[Link]()),
]);

2.7 ES6+ Features — Know These


// Template literals
const msg = `Hello ${name}, you are ${age} years old`;

// Ternary operator
const label = isLoggedIn ? 'Logout' : 'Login';

// Short-circuit evaluation
isLoggedIn && <Dashboard />; // render only if true (used in React)

// Array destructuring
const [first, second, ...rest] = [1, 2, 3, 4];

// Import / Export (modules)


export const greet = () => {}; // named export
export default App; // default export
import App from './App'; // import default
import { greet } from './utils'; // import named

// for...of loop
for (const item of items) { [Link](item); }

// [Link] / values / entries


[Link](user) // ['name', 'age', 'city']
[Link](user) // ['Ravi', 25, 'Chennai']
[Link](user) // [['name','Ravi'], ['age',25], ...]

■■ Interview Traps

• == vs === : use === always (checks type + value). 0 == false is true, 0 === false is false.
• typeof null === 'object' — this is a known JS bug, not a feature.
• Arrays are objects: typeof [] === 'object'. Use [Link]([]) to check.
• this keyword: in arrow functions, this is lexically bound (from parent scope). In regular
functions, this depends on how it's called.
• Hoisting: var and function declarations are hoisted. let/const are NOT.
• Closure: a function that remembers variables from its outer scope even after that scope has
finished executing.
Chapter 3 — [Link]

[Link] is a JavaScript runtime built on Chrome's V8 engine. It lets you run JavaScript on the
server — outside the browser.

3.1 Key Concepts


Concept What It Means

JS runs on one thread but handles concurrency


Single-threaded via Event Loop

File reads, DB calls, network — all async,


Non-blocking I/O doesn't freeze

Node Package Manager — install libraries


npm (express, mongoose, etc.)

Project config file — lists dependencies, scripts,


[Link] metadata

node_modules Where installed packages live (never push to git)

require/[Link] — older Node module


CommonJS system

import/export — modern syntax (add


ES Modules type:module in [Link])

3.2 Essential Commands


node --version # check Node version
npm --version # check npm version

# Project setup
mkdir my-app && cd my-app
npm init -y # create [Link] (skip questions)

# Install packages
npm install express # production dependency
npm install nodemon --save-dev # dev-only dependency
npm install mongoose dotenv cors

# Run files
node [Link] # run a file
npx nodemon [Link] # run with auto-restart on file changes
# Scripts in [Link]
# "scripts": { "start": "node [Link]", "dev": "nodemon [Link]" }
npm start # run start script
npm run dev # run dev script

# See installed packages


npm list
npm list --depth=0 # top-level only

3.3 Basic [Link] Server (without Express)


const http = require('http');

const server = [Link]((req, res) => {


[Link](200, { 'Content-Type': 'application/json' });
[Link]([Link]({ message: 'Hello from Node!' }));
});

[Link](3000, () => {
[Link]('Server running on [Link]
});

3.4 Built-in Modules


Module Purpose

fs File system — read/write files

path Handle file paths cross-platform

os Operating system info (memory, CPU)

http Create HTTP servers

events EventEmitter — custom event system

crypto Hashing, encryption

process [Link], [Link], [Link]()

const fs = require('fs');
const path = require('path');

// Read a file
[Link]('[Link]', 'utf8', (err, data) => {
if (err) throw err;
[Link](data);
});

// Path join (cross-platform)


const fullPath = [Link](__dirname, 'files', '[Link]');

// Environment variables
[Link]; // from .env file
[Link].NODE_ENV; // 'development' | 'production'
Chapter 4 — [Link]

Express is a minimal, fast web framework for [Link]. It handles HTTP routing, middleware, and
responses. In MERN, Express IS your backend API.

4.1 Basic Express Server


const express = require('express');
const app = express();

// Middleware — must be before routes


[Link]([Link]()); // parse JSON request bodies
[Link]([Link]({ extended: true })); // parse form data

// CORS — allow React frontend to call this API


const cors = require('cors');
[Link](cors()); // allow all origins (dev only)
// OR specific origin:
[Link](cors({ origin: '[Link] }));

[Link](5000, () => [Link]('API running on port 5000'));

4.2 CRUD Routes — The Full Pattern


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

// GET single user by ID


[Link]('/api/users/:id', async (req, res) => {
const user = await [Link]([Link]);
if (!user) return [Link](404).json({ message: 'Not found' });
[Link](user);
});

// POST create user


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

// PUT 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' });
});

4.3 Middleware — Important Concept


Middleware is a function that runs between the request arriving and the response being sent. It
has access to req, res, and next.

// Logger middleware
[Link]((req, res, next) => {
[Link](`${[Link]} ${[Link]} - ${new Date()}`);
next(); // MUST call next() or request hangs
});

// Auth middleware (protect routes)


const authMiddleware = (req, res, next) => {
const token = [Link];
if (!token) return [Link](401).json({ message: 'Unauthorized' });
// verify token ...
next();
};

// Apply to specific route


[Link]('/api/profile', authMiddleware, (req, res) => {
[Link]({ user: [Link] });
});

4.4 Router — Organizing Routes


// routes/[Link]
const router = require('express').Router();
const { getUsers, createUser } = require('../controllers/userController');

[Link]('/', getUsers);
[Link]('/', createUser);

[Link] = router;

// [Link] — mount the router


const userRoutes = require('./routes/userRoutes');
[Link]('/api/users', userRoutes);
// Now: GET /api/users → getUsers
// POST /api/users → createUser
4.5 HTTP Status Codes — Know These
Status Code When to Use

200 OK Successful GET or PUT

201 Created Successful POST (new resource created)

204 No Content Successful DELETE (no body returned)

400 Bad Request Client sent invalid data

401 Unauthorized Not authenticated (no/invalid token)

403 Forbidden Authenticated but no permission

404 Not Found Resource doesn't exist

409 Conflict Duplicate — e.g. email already exists

500 Internal Server Error Server crashed / bug in your code


Chapter 5 — MongoDB & Mongoose

5.1 SQL vs MongoDB


SQL (MySQL/PostgreSQL) MongoDB

Table Collection

Row Document

Column Field

Primary Key _id (auto, ObjectId)

JOIN populate() or $lookup

Schema Flexible (optional)

SQL query JSON-like query

5.2 Connect MongoDB with Mongoose


npm install mongoose

// [Link]
const mongoose = require('mongoose');

const connectDB = async () => {


try {
await [Link]([Link].MONGO_URI);
[Link]('MongoDB connected');
} catch (err) {
[Link]([Link]);
[Link](1);
}
};

[Link] = connectDB;

// [Link]
const connectDB = require('./db');
connectDB();

// .env file
MONGO_URI=mongodb+srv://user:pass@[Link]/mydb

5.3 Schema & Model


const mongoose = require('mongoose');

const userSchema = new [Link]({


name: { type: String, required: true, trim: true },
email: { type: String, required: true, unique: true, lowercase: true },
password: { type: String, required: true, minlength: 6 },
age: { type: Number, min: 0, max: 120 },
role: { type: String, enum: ['user', 'admin'], default: 'user' },
isActive: { type: Boolean, default: true },
createdAt: { type: Date, default: [Link] },
address: {
street: String,
city: String,
},
tags: [String], // array of strings
}, { timestamps: true }); // adds createdAt, updatedAt automatically

const User = [Link]('User', userSchema);


[Link] = User;

5.4 CRUD Operations


const User = require('./models/User');
// CREATE
const user = await [Link]({ name: 'Ravi', email: 'r@[Link]' });
const user = new User({ name: 'Ravi' });
await [Link]();

// READ
const all = await [Link](); // all documents
const one = await [Link]('someId'); // by _id
const found = await [Link]({ email: 'r@[Link]' });
const active = await [Link]({ isActive: true }); // filter

// Projections (select fields)


await [Link]().select('name email -_id'); // include/exclude

// Sort, limit, skip (pagination)


await [Link]().sort({ createdAt: -1 }).limit(10).skip(0);

// UPDATE
await [Link](id, { name: 'Kumar' }, { new: true });
await [Link]({ isActive: false }, { $set: { role: 'guest' } });

// DELETE
await [Link](id);
await [Link]({ isActive: false });

// COUNT
const total = await [Link]({ isActive: true });

5.5 Query Operators


Operator Usage
Greater than / greater than or equal: { age: { $gt:
$gt / $gte 18 } }

$lt / $lte Less than / less than or equal

$eq / $ne Equal / not equal

$in Value in array: { role: { $in: ['admin','user'] } }

$nin Value NOT in array

$or { $or: [{ age: 18 }, { name: 'Ravi' }] }

$and { $and: [{ age: {$gt:18} }, { isActive: true }] }

{ name: { $regex: 'raj', $options: 'i' } }


$regex (case-insensitive)

$set Update specific fields: { $set: { name: 'Kumar' } }

$push Add to array: { $push: { tags: 'nodejs' } }

$pull Remove from array: { $pull: { tags: 'old' } }


Chapter 6 — React

React is a JavaScript library for building user interfaces. It uses components — reusable,
self-contained pieces of UI.

6.1 Setup
# Create React app (official tool)
npx create-react-app my-app
cd my-app
npm start # runs on [Link]

# Or use Vite (faster, modern)


npm create vite@latest my-app -- --template react
cd my-app && npm install && npm run dev

6.2 JSX — JavaScript + HTML


JSX looks like HTML but it IS JavaScript. It gets compiled to [Link]() calls.

// JSX rules:
// 1. Must return ONE root element (use <div> or <> fragment)
// 2. Use className instead of class
// 3. Use htmlFor instead of for (label)
// 4. Close ALL tags: <img /> <br /> <input />
// 5. JS expressions go in { }

const App = () => {


const name = 'Ravi';
const items = ['React', 'Node', 'MongoDB'];

return (
<div className='container'>
<h1>Hello {name}</h1>
<p>{2 + 2}</p>
{[Link](item => <li key={item}>{item}</li>)}
{name === 'Ravi' && <span>Welcome back!</span>}
{isLoggedIn ? <Dashboard /> : <Login />}
</div>
);
};

6.3 Props — Passing Data to Components


// Parent component passes data
const App = () => {
return <UserCard name='Ravi' age={25} isAdmin={true} />;
};

// Child receives props


const UserCard = ({ name, age, isAdmin }) => {
return (
<div>
<h2>{name}</h2>
<p>Age: {age}</p>
{isAdmin && <span>Admin</span>}
</div>
);
};

// Props are READ-ONLY — child cannot modify them


// Default props
[Link] = { age: 18 };
// Or in function signature:
const UserCard = ({ name, age = 18 }) => {};

6.4 useState — State Management


import { useState } from 'react';

const Counter = () => {


const [count, setCount] = useState(0); // [value, setter]
// 0 = initial value
const increment = () => setCount(count + 1);
const reset = () => setCount(0);

return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>+</button>
<button onClick={reset}>Reset</button>
</div>
);
};

// Object state
const [user, setUser] = useState({ name: '', email: '' });
// ALWAYS spread to update — don't mutate directly
setUser({ ...user, name: 'Ravi' });

// Array state
const [items, setItems] = useState([]);
setItems([...items, newItem]); // add
setItems([Link](i => [Link] !== id)); // remove

6.5 useEffect — Side Effects


import { useEffect, useState } from 'react';
const UserList = () => {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);

// Runs ONCE when component mounts ([] dependency array)


useEffect(() => {
const fetchUsers = async () => {
const res = await fetch('[Link]
const data = await [Link]();
setUsers(data);
setLoading(false);
};
fetchUsers();
}, []);

// Runs when 'userId' changes


useEffect(() => {
fetchUser(userId);
}, [userId]);

// Cleanup function (for subscriptions, timers, etc.)


useEffect(() => {
const timer = setInterval(tick, 1000);
return () => clearInterval(timer); // cleanup on unmount
}, []);

if (loading) return <p>Loading...</p>;


return <ul>{[Link](u => <li key={u._id}>{[Link]}</li>)}</ul>;
};

6.6 Handling Forms


const LoginForm = () => {
const [formData, setFormData] = useState({ email: '', password: '' });

const handleChange = (e) => {


setFormData({ ...formData, [[Link]]: [Link] });
};

const handleSubmit = async (e) => {


[Link](); // prevent page reload!
const res = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: [Link](formData),
});
const data = await [Link]();
[Link](data);
};

return (
<form onSubmit={handleSubmit}>
<input name='email' value={[Link]}
onChange={handleChange} type='email' />
<input name='password' value={[Link]}
onChange={handleChange} type='password' />
<button type='submit'>Login</button>
</form>
);
};

6.7 React Router — Navigation


npm install react-router-dom

// [Link]
import { BrowserRouter, Routes, Route, Link, useNavigate } from 'react-router-dom';

const App = () => (


<BrowserRouter>
<nav>
<Link to='/'>Home</Link>
<Link to='/users'>Users</Link>
</nav>
<Routes>
<Route path='/' element={<Home />} />
<Route path='/users' element={<UserList />} />
<Route path='/users/:id' element={<UserDetail />} /> {/* dynamic */}
<Route path='*' element={<NotFound />} /> {/* 404 */}
</Routes>
</BrowserRouter>
);

// In a component — read URL param


import { useParams } from 'react-router-dom';
const { id } = useParams(); // from /users/:id

// Programmatic navigation
const navigate = useNavigate();
navigate('/dashboard');
navigate(-1); // go back

6.8 Other Hooks


Hook Purpose

Access DOM elements directly: const ref =


useRef useRef();

Share state globally without prop-drilling (pair


useContext with createContext)

useReducer Complex state logic (like Redux but built-in)


Cache expensive calculations: useMemo(() =>
useMemo compute(), [dep])

Cache function reference: useCallback(() => fn(),


useCallback [dep])

useId Generate unique IDs for accessibility


Chapter 7 — Full Stack Connection

7.1 Project Structure


my-mern-app/
backend/
models/ # Mongoose schemas
routes/ # Express routers
controllers/ # Route handlers
middleware/ # Auth, logging, etc.
.env # MONGO_URI, JWT_SECRET, PORT
[Link] # Express app setup
[Link] # Entry point — connectDB + listen
frontend/
src/
components/ # Reusable UI pieces
pages/ # Page components
hooks/ # Custom hooks
context/ # Global state
api/ # API call functions
[Link]

7.2 Backend Entry Point ([Link])


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

const app = express();


[Link]([Link]());
[Link](cors({ origin: '[Link] }));

// Routes
[Link]('/api/users', require('./routes/userRoutes'));
[Link]('/api/posts', require('./routes/postRoutes'));

// Connect DB then start server


[Link]([Link].MONGO_URI)
.then(() => [Link]([Link] || 5000,
() => [Link]('Server + DB ready')))
.catch(err => [Link](err));

7.3 React API Calls (Frontend)


// src/api/[Link] — centralize all API calls
const BASE_URL = '[Link]
export const getUsers = async () => {
const res = await fetch(`${BASE_URL}/users`);
if (![Link]) throw new Error('Failed to fetch');
return [Link]();
};

export const createUser = async (userData) => {


const res = await fetch(`${BASE_URL}/users`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: [Link](userData),
});
return [Link]();
};

// Using axios (cleaner alternative)


npm install axios

import axios from 'axios';


const { data } = await [Link]('/api/users');
const { data } = await [Link]('/api/users', { name, email });

7.4 Authentication with JWT


JWT (JSON Web Token) is the standard way to handle auth in MERN.

npm install jsonwebtoken bcryptjs

// Backend: hash password on register


const bcrypt = require('bcryptjs');
const salt = await [Link](10);
[Link] = await [Link](password, salt);

// Compare on login
const isMatch = await [Link](enteredPassword, [Link]);

// Generate JWT token


const jwt = require('jsonwebtoken');
const token = [Link](
{ id: user._id, role: [Link] },
[Link].JWT_SECRET,
{ expiresIn: '7d' }
);
[Link]({ token, user });

// Auth middleware — verify token


const protect = (req, res, next) => {
const token = [Link]?.split(' ')[1]; // 'Bearer <token>'
if (!token) return [Link](401).json({ message: 'No token' });
try {
[Link] = [Link](token, [Link].JWT_SECRET);
next();
} catch {
[Link](401).json({ message: 'Invalid token' });
}
};

// React: store token and send it


[Link]('token', [Link]);
headers: { Authorization: `Bearer ${[Link]('token')}` }
Chapter 8 — Top Interview Q&A;

JavaScript Q&A;
Q1: What is the difference between == and ===?
== compares values with type coercion (0 == false is true). === compares value AND type (0
=== false is false). Always use ===.

Q2: What is a closure?


A function that remembers variables from its outer scope even after the outer function has
finished. Example: counter functions that increment an internal variable.

Q3: What is the event loop?


JS is single-threaded. The event loop lets it handle async code by putting callbacks in a queue
and running them after the call stack is empty. This makes [Link] non-blocking.

Q4: What is hoisting?


JS moves var declarations and function declarations to the top of their scope before execution.
let/const are hoisted but NOT initialized (temporal dead zone).

Q5: Difference between null and undefined?


undefined means a variable was declared but not assigned. null is an intentional empty value
assigned by the programmer.

Q6: What is a Promise?


An object representing an eventual value (resolved or rejected). Handles async operations.
States: pending, fulfilled, rejected.

Q7: What is async/await?


Syntactic sugar over Promises. Makes async code look synchronous. await pauses execution
until the Promise resolves. Must be inside an async function.

Q8: What is the spread operator?


... spreads array/object elements. Used to copy, merge, or add items without mutating the
original: [...arr, newItem] or {...obj, newProp: value}.

Q9: What is destructuring?


Extract values from arrays/objects into variables. const {name, age} = user; or const [first,
second] = arr;

Q10: What is a callback?


A function passed as an argument to another function, called after an operation completes. The
older way to handle async code before Promises.

React Q&A;
Q1: What is React?
A JavaScript library (not a framework) for building UIs. Created by Facebook. Uses a virtual
DOM, component-based architecture, and unidirectional data flow.

Q2: What is the virtual DOM?


A lightweight JS copy of the real DOM. When state changes, React re-renders to the virtual DOM
first, diffs it with the previous version, and only updates the changed real DOM nodes — making
it fast.

Q3: Props vs State?


Props are data passed FROM parent TO child — read-only. State is data managed INSIDE a
component — can be updated with setState/useState, causing a re-render.

Q4: What is a React Hook?


Functions that let functional components use state and lifecycle features. Rules: only call at top
level, only in React functions. Common: useState, useEffect, useRef, useContext.

Q5: What is useEffect used for?


Running side effects in functional components: API calls, subscriptions, timers, DOM
manipulation. The dependency array controls when it runs: [] = once, [dep] = when dep changes,
none = every render.

Q6: What is key in lists?


A special prop that helps React identify which list items changed. Must be unique among
siblings. Use the item's ID, not the index (using index causes bugs on reordering).

Q7: Controlled vs uncontrolled components?


Controlled: React state controls the form input value (value + onChange). Uncontrolled: DOM
manages its own state, accessed via ref. Always prefer controlled components.

Q8: What is prop drilling?


Passing props through many component layers to reach a deeply nested child. Solutions: React
Context, state management libraries (Redux, Zustand).

[Link] & Express Q&A;


Q1: What is [Link]?
A JavaScript runtime built on Chrome's V8 engine that lets JS run on the server. Single-threaded
but handles concurrency via event loop and non-blocking I/O.

Q2: What is npm?


Node Package Manager. Manages project dependencies, runs scripts, and publishes packages.
[Link] lists all dependencies; [Link] locks exact versions.

Q3: What is middleware in Express?


Functions that run between the request and the response. Can modify req/res, end the request
cycle, or call next() to pass to the next middleware. Used for auth, logging, CORS, parsing.

Q4: What is CORS?


Cross-Origin Resource Sharing. Browser security policy that blocks requests from a different
domain. In MERN, React (port 3000) calling Express (port 5000) triggers CORS. Fix:
[Link](cors()).

Q5: What is REST API?


Representational State Transfer. Architectural style using HTTP methods (GET, POST, PUT,
DELETE) and URLs to perform CRUD operations. Stateless — each request is independent.

Q6: What is JWT?


JSON Web Token. A compact, self-contained token for authentication. Contains encoded user
info (payload). Signed with a secret key. Sent in Authorization header: 'Bearer '.

MongoDB Q&A;
Q1: What is MongoDB?
A NoSQL document database that stores data as BSON (Binary JSON) documents in
collections. Schema-flexible — documents in the same collection can have different fields.

Q2: What is Mongoose?


An ODM (Object Data Modeling) library for MongoDB and [Link]. Provides schema validation,
type casting, query building, and middleware (pre/post hooks).

Q3: What is an index in MongoDB?


A data structure that improves query speed. Without index = full collection scan. Common: {
email: 1 } for exact match, { createdAt: -1 } for sort. unique: true enforces uniqueness.

Q4: What is populate() in Mongoose?


Replaces a referenced ObjectId with the actual document from another collection — like a SQL
JOIN. Example: [Link]().populate('author').
Chapter 9 — Commands Cheat Sheet

Node / npm
node -v && npm -v # check versions
npm init -y # create [Link]
npm install <pkg> # add dependency
npm install <pkg> -D # add dev dependency
npm install # install all from [Link]
npm run <script> # run npm script
npm start # run 'start' script
npx <command> # run without installing globally
npm uninstall <pkg> # remove package
npm update # update packages
npm list --depth=0 # list installed packages

Git (you'll need this)


git init # initialize repo
git add . # stage all changes
git commit -m "message" # commit
git push origin main # push to GitHub
git clone <url> # clone a repo
git status # see changed files
git log --oneline # see commit history

# .gitignore (create this file, add these)


node_modules/
.env
dist/
build/

React
npx create-react-app my-app # create React app
npm create vite@latest my-app # create with Vite (faster)
npm start # start dev server (CRA)
npm run dev # start dev server (Vite)
npm run build # production build
npm install react-router-dom # routing
npm install axios # HTTP client
npm install @mui/material # Material UI components
npm install tailwindcss # Tailwind CSS

Express / Backend
npm install express cors dotenv mongoose
npm install nodemon --save-dev
npm install jsonwebtoken bcryptjs # auth
npm install express-validator # input validation
npm install multer # file uploads

# Postman / Thunder Client — test your API without React


GET [Link]
POST [Link]
Body (JSON): { 'name': 'Ravi', 'email': 'r@[Link]' }

MongoDB
# MongoDB shell commands (mongosh)
show dbs # list databases
use myapp # switch/create database
show collections # list collections
[Link]() # find all documents
[Link]().pretty() # formatted output
[Link]({name:'Ravi'})
[Link]({name:'Ravi'})
[Link]() # delete collection

# MongoDB Atlas — free cloud DB


# 1. Create account at [Link]/atlas
# 2. Create cluster (free tier)
# 3. Get connection string for .env
MONGO_URI=mongodb+srv://user:pass@[Link]/dbname
Chapter 10 — Platforms to Learn Fast

Best Free Resources — Ranked by Speed


Platform What to Learn Time Needed Link

YouTube MERN Crash Course 4-6 hours Search: 'MERN Stack Crash Course Traversy Media
Traversy Media (all 4 in one video)

YouTube React, Node, MongoDB 2-3 hrs each [Link]/@NetNinja


Net Ninja individual series

freeCodeCamp JavaScript Algorithms Self-paced [Link]


React Certificate

The Odin Project Full MERN path Self-paced [Link]


project-based

MongoDB University MongoDB Basics 4-6 hours [Link]


(free + official cert)

[Link] React & Node roadmaps 30 mins [Link]/react


visual learning

MDN Web Docs JS reference On demand [Link]


best documentation

Your 2-Day Study Plan


Day 1 — Backend Focus
• Morning (3h): Watch Traversy Media MERN Crash Course — Part 1 (Node + Express)
• Afternoon (3h): Build a basic Express REST API with 5 routes (GET, POST, PUT, DELETE)
• Evening (2h): Connect MongoDB Atlas, create a Mongoose schema, test with Postman
• Night (1h): Review JS: closures, promises, async/await, array methods

Day 2 — Frontend + Full Stack


• Morning (3h): Watch Traversy Media MERN Crash Course — Part 2 (React + Full Stack)
• Afternoon (3h): Build a React frontend that calls your Express API
• Evening (2h): Add JWT authentication (register + login + protected route)
• Night (1h): Practice interview Q&A; from Chapter 8 of this guide

■ INTERVIEW TIP: If you don't know something, say: 'I understand the concept — [explain it] — and I'd
implement it by [describe approach]. I'm actively building with it.'
Remember: JavaScript is the same language across ALL 4 layers. Master JS basics and the rest
falls into place. You've got this!

You might also like