0% found this document useful (0 votes)
18 views25 pages

MEAN Stack Complete Notes

The document provides comprehensive study notes for the MEAN stack, covering key technologies such as MongoDB, Express.js, Angular, and Node.js across seven chapters with a total of 45 teaching hours. It includes an overview of web development, installation guides, CRUD operations, and best practices for each technology. Additionally, it offers exam tips and detailed explanations of concepts like NoSQL databases, middleware, and REST APIs.

Uploaded by

brahman7878
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)
18 views25 pages

MEAN Stack Complete Notes

The document provides comprehensive study notes for the MEAN stack, covering key technologies such as MongoDB, Express.js, Angular, and Node.js across seven chapters with a total of 45 teaching hours. It includes an overview of web development, installation guides, CRUD operations, and best practices for each technology. Additionally, it offers exam tips and detailed explanations of concepts like NoSQL databases, middleware, and REST APIs.

Uploaded by

brahman7878
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

MEAN Stack

Web Development
Complete Study Notes

(MongoDB · [Link] · Angular · [Link])

Comprehensive Exam Preparation Guide

All 7 Chapters · 45 Teaching Hours · 100% Weightage Coverage

Ch Topic W% Hrs

1 Intro to Web Dev & MEAN Stack 4% 2

2 MongoDB 20% 10

3 [Link] & Express JS 20% 10

4 Angular 30% 13

5 Integration 10% 3

6 Deployment & Best Practices 6% 3

7 Final Project 10% 4

TOTAL 100% 45

MEAN Stack Study Notes | Page 1


uction to Web Development &
Weightage: 4% | Teaching Ho
e MEAN Stack

■ 1.1 Overview of Web Development


Web development is the process of building and maintaining websites and web applications. It is broadly
classified into three areas:
• Frontend (Client-Side): Everything the user sees – HTML, CSS, JavaScript, Angular/React.
• Backend (Server-Side): Business logic, APIs, databases – [Link], [Link].
• Database: Stores data persistently – MongoDB, MySQL, PostgreSQL.
• Full-Stack: Developer who works on both frontend and backend.

Key Web Technologies


• HTTP/HTTPS: Hypertext Transfer Protocol – communication between browser and server. HTTPS is the
secure version using SSL/TLS.
• REST API: Representational State Transfer – architectural style for APIs using HTTP methods (GET,
POST, PUT, DELETE).
• JSON: JavaScript Object Notation – lightweight data-interchange format used between frontend and
backend.
• SPA (Single Page Application): Web app that loads a single HTML page and dynamically updates
content without full page reload (Angular does this).

■ 1.2 Introduction to the MEAN Stack


The MEAN stack is a full-stack JavaScript framework for building dynamic web applications. All four
technologies use JavaScript, making it a unified language for the entire application.

Letter Technology Role Description

M MongoDB NoSQL Document Database Stores application data as JSON-like BSON documents

E [Link] Web Application Framework Minimalist [Link] framework for building REST APIs

A Angular Frontend Framework TypeScript-based SPA framework by Google for UI

N [Link] JavaScript Runtime Runs JavaScript on the server using Chrome V8 engine

■ 1.3 Setting Up the Development Environment


• Install [Link] (includes npm – Node Package Manager) from [Link]
• Install MongoDB Community Server from [Link]
• Install Angular CLI: npm install -g @angular/cli
• Install VS Code (recommended IDE) with extensions: ESLint, Prettier, Angular Language Service
• Install Postman – for testing REST APIs
• Install MongoDB Compass – GUI for MongoDB

Verify Installation Commands


node --version # Check [Link] version
npm --version # Check npm version
mongod --version # Check MongoDB version

MEAN Stack Study Notes | Page 2


ng version # Check Angular CLI version

★ EXAM TIPS:
• MEAN stands for MongoDB, [Link], Angular, [Link] – all use JavaScript.
• Difference between SPA and traditional web apps – SPA does NOT reload the full page.
• HTTP Methods: GET (read), POST (create), PUT (update), DELETE (remove).
• npm is Node Package Manager used to install dependencies.
• Angular CLI command: 'ng new project-name' creates a new Angular project.

MEAN Stack Study Notes | Page 3


pter 2: MongoDB Weightage: 20% | Teaching Ho

■ 2.1 Introduction to NoSQL Databases


NoSQL (Not Only SQL) databases are non-relational databases that store data in formats other than tabular
rows and columns. They are designed for scalability, flexibility, and high-volume data.

Feature SQL (Relational) NoSQL (MongoDB)

Data Format Tables with rows & columns Documents (JSON/BSON)

Schema Fixed schema (predefined) Dynamic / Flexible schema

Scalability Vertical (scale up) Horizontal (scale out)

Query Language SQL MongoDB Query Language (MQL)

Relationships Foreign keys / Joins Embedded documents / References

Examples MySQL, PostgreSQL, Oracle MongoDB, CouchDB, Firebase

Best For Structured data, transactions Unstructured/semi-structured, big data

■ 2.2 MongoDB Architecture & Key Concepts


• Database: Top-level container that holds collections (like a database in SQL).
• Collection: Group of MongoDB documents (equivalent to a SQL table). Schema-less.
• Document: A single record in BSON format (Binary JSON). Like a row in SQL.
• Field: A key-value pair within a document (like a column in SQL).
• _id: Primary key – automatically generated unique identifier (ObjectId) for every document.
• BSON: Binary JSON – MongoDB's storage format. Supports more data types than JSON (e.g., Date,
Binary).

Sample MongoDB Document


{
"_id": ObjectId("64a1b2c3d4e5f6789abcdef0"),
"name": "John Doe",
"email": "john@[Link]",
"age": 28,
"address": {
"city": "Mumbai",
"state": "Maharashtra"
},
"courses": ["MongoDB", "[Link]", "Angular"],
"createdAt": ISODate("2024-01-15T10:30:00Z")
}

■ 2.3 Installation and Configuration


• Download MongoDB Community Edition from [Link]/try/download/community
• Start MongoDB service: mongod (starts the MongoDB daemon/server)
• Connect via shell: mongosh (MongoDB Shell)
• Default port: 27017
• Data directory: /data/db (Linux/Mac) or C:\data\db (Windows)
• MongoDB Compass – graphical UI tool for database management

MEAN Stack Study Notes | Page 4


• mongoimport / mongoexport – CLI tools for data import/export

■ 2.4 CRUD Operations in MongoDB


CRUD = Create, Read, Update, Delete – the four basic database operations.

CREATE – Insert Documents


// Insert a single document
[Link]({ name: "Alice", age: 20, grade: "A" })

// Insert multiple documents


[Link]([
{ name: "Bob", age: 21, grade: "B" },
{ name: "Charlie", age: 22, grade: "A" }
])

READ – Query Documents


// Find all documents
[Link]()

// Find with condition (WHERE equivalent)


[Link]({ grade: "A" })

// Find with projection (select specific fields)


[Link]({ grade: "A" }, { name: 1, age: 1, _id: 0 })

// Find one document


[Link]({ name: "Alice" })

// Comparison operators
[Link]({ age: { $gt: 20 } }) // age > 20
[Link]({ age: { $gte: 20, $lte: 25 } }) // 20 <= age <= 25

UPDATE – Modify Documents


// Update one document
[Link](
{ name: "Alice" }, // filter
{ $set: { grade: "A+" } } // update operator
)

// Update multiple documents


[Link]({ grade: "B" }, { $set: { status: "average" } })

// Replace entire document


[Link]({ name: "Bob" }, { name: "Bob", age: 22, grade: "A" })

// $inc – increment a field


[Link]({ name: "Alice" }, { $inc: { age: 1 } })

DELETE – Remove Documents


// Delete one document
[Link]({ name: "Charlie" })

// Delete multiple documents


[Link]({ grade: "C" })

// Delete all documents in collection

MEAN Stack Study Notes | Page 5


[Link]({})

■ 2.5 Indexing and Querying


Indexes improve query performance by allowing MongoDB to quickly locate data without scanning every
document (full collection scan).

Types of Indexes
• Single Field Index: Index on one field. Default: _id has an index. [Link]({ field: 1 })
• Compound Index: Index on multiple fields. [Link]({ field1: 1, field2: -1 })
• Unique Index: Ensures no duplicate values. [Link]({ email: 1 }, { unique: true })
• Text Index: Full-text search on string fields. [Link]({ name: 'text' })
• Sparse Index: Only indexes documents that have the indexed field.
• TTL Index: Automatically deletes documents after a time period – used for session data.
// Create index on 'name' field (ascending)
[Link]({ name: 1 })

// View all indexes


[Link]()

// Drop an index
[Link]("name_1")

// Explain query – check if index is used


[Link]({ name: "Alice" }).explain("executionStats")

Advanced Query Operators


Term / Concept Explanation

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

$lt / $lte Less than / Less than or equal { age: { $lt: 60 } }

$eq / $ne Equal / Not equal { grade: { $ne: "F" } }

$in Matches any value in array { grade: { $in: ["A","B"] } }

$nin Not in array { grade: { $nin: ["D","F"] } }

$and Logical AND { $and: [{age:{$gt:18}},{grade:"A"}] }

$or Logical OR { $or: [{grade:"A"},{grade:"B"}] }

$not Logical NOT { age: { $not: { $gt: 30 } } }

$exists Field exists or not { email: { $exists: true } }

$regex Pattern matching { name: { $regex: /^A/ } }

■ 2.6 Schema Design and Data Modeling

Embedding vs. Referencing


Two strategies for handling relationships in MongoDB:

• Embedding (Denormalization): Store related data within the same document. Faster reads (one query).
Use when data is always accessed together and not too large. E.g., Address inside User document.

MEAN Stack Study Notes | Page 6


• Referencing (Normalization): Store related data in separate collections and link via _id. Use when related
data is large, shared, or frequently updated independently. E.g., Orders referencing Product by product_id.

Aggregation Pipeline
Aggregation processes data and returns computed results. It uses a pipeline of stages:
[Link]([
{ $match: { status: 'completed' } }, // Filter stage
{ $group: { _id: '$customer',
total: { $sum: '$amount' } } }, // Group & sum
{ $sort: { total: -1 } }, // Sort descending
{ $limit: 5 } // Top 5 results
])

★ EXAM TIPS:
• MongoDB stores data as BSON documents. Collections = SQL tables, Documents = SQL rows.
• CRUD: insertOne/insertMany, find/findOne, updateOne/updateMany, deleteOne/deleteMany.
• Common update operators: $set, $unset, $inc, $push, $pull, $addToSet.
• $gt, $lt, $gte, $lte, $eq, $ne, $in, $or, $and – all query operators.
• Indexes speed up reads but slow down writes. Use explain() to check query performance.
• Aggregation pipeline stages: $match, $group, $sort, $project, $limit, $skip, $lookup.
• Embedding = faster reads; Referencing = more flexibility and data integrity.

MEAN Stack Study Notes | Page 7


[Link] & Express JS Weightage: 20% | Teaching Ho

■ 3.1 Introduction to [Link]


[Link] is an open-source, cross-platform JavaScript runtime environment built on Chrome's V8 JavaScript
engine. It allows running JavaScript outside the browser (on the server).

• Event-Driven: [Link] uses an event loop to handle concurrent requests without creating new threads.
• Non-Blocking I/O: Operations like file reading, database queries do not block execution –
callbacks/promises are used.
• Single-Threaded: Uses one main thread but handles concurrency via the event loop.
• npm (Node Package Manager): World's largest software registry with 1M+ packages. npm install .
• CommonJS Modules: require() to import, [Link] to export.
• ES6 Modules: import/export syntax (requires 'type':'module' in [Link]).

Built-in [Link] Modules


Term / Concept Explanation

fs File System readFile, writeFile, appendFile, unlink, mkdir

http HTTP Server createServer, request, response

path File Paths join, resolve, basename, dirname, extname

os Operating System platform, arch, cpus, freemem, hostname

events Event Emitter on, emit, removeListener

crypto Cryptography hash, encrypt, decrypt, randomBytes

url URL Parsing parse, format, resolve

Basic HTTP Server in [Link]


const http = require('http');

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


[Link](200, { 'Content-Type': 'text/plain' });
[Link]('Hello World from [Link]!');
});

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

■ 3.2 Introduction to [Link]


[Link] is a minimal and flexible [Link] web application framework. It provides a robust set of features for
building web and mobile applications including REST APIs.

• Install Express: npm install express


• Express simplifies HTTP request handling compared to raw [Link] http module
• Supports middleware, routing, template engines, static file serving
• Most popular [Link] framework – used in MEAN/MERN stacks

Basic [Link] Server

MEAN Stack Study Notes | Page 8


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

[Link]([Link]()); // Middleware to parse JSON body

// Routes
[Link]('/', (req, res) => {
[Link]('Hello from Express!');
});

[Link]('/users', (req, res) => {


[Link]([{ id: 1, name: 'Alice' }]);
});

[Link](3000, () => [Link]('Server on port 3000'));

■ 3.3 Middleware and Routing


Middleware are functions that have access to the request (req), response (res), and next middleware in the
application's request-response cycle.

Types of Middleware
• Application-level: [Link]() – applied to all routes or specific path.
• Router-level: [Link]() – applied to specific router.
• Built-in: [Link](), [Link](), [Link]() – provided by Express.
• Third-party: morgan (logging), cors, helmet, body-parser – installed via npm.
• Error-handling: Has 4 parameters (err, req, res, next) – must be defined last.
// Custom middleware – runs on every request
[Link]((req, res, next) => {
[Link](`${[Link]} ${[Link]} - ${new Date().toISOString()}`);
next(); // MUST call next() to pass to next middleware
});

// Router-level middleware
const router = [Link]();
[Link]('/profile', (req, res) => [Link]({ user: 'Alice' }));
[Link]('/api', router); // Mounted at /api/profile

// Error handling middleware (4 params)


[Link]((err, req, res, next) => {
[Link](500).json({ error: [Link] });
});

REST API Route Examples


// CRUD Routes for /api/students
[Link]('/api/students', getAllStudents); // GET all
[Link]('/api/students/:id', getStudentById); // GET by ID
[Link]('/api/students', createStudent); // CREATE
[Link]('/api/students/:id', updateStudent); // UPDATE
[Link]('/api/students/:id', deleteStudent); // DELETE

// Access route params and query strings


[Link]('/students/:id', (req, res) => {
const id = [Link]; // Route parameter
const page = [Link]; // Query string ?page=2
const data = [Link]; // POST body (JSON)

MEAN Stack Study Notes | Page 9


});

■ 3.4 Authentication and Security with [Link]


[Link] is authentication middleware for [Link] that supports 500+ authentication strategies.

• JWT (JSON Web Token): Stateless authentication. Server issues a signed token; client sends it with every
request in the Authorization header. Format: [Link]
• Local Strategy: Username + Password authentication against database.
• OAuth Strategy: Login with Google, Facebook, GitHub, etc.
• bcrypt: Password hashing library. Never store plain-text passwords. [Link](password, 10) creates a
salted hash.

JWT Authentication Flow


const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');

// Login route – generate JWT


[Link]('/login', async (req, res) => {
const { email, password } = [Link];
const user = await [Link]({ email });
const valid = await [Link](password, [Link]);
if (!valid) return [Link](401).json({ error: 'Invalid credentials' });
const token = [Link]({ userId: user._id }, [Link].JWT_SECRET, { expiresIn: '1h' }
);
[Link]({ token });
});

// Middleware to protect routes


const authMiddleware = (req, res, next) => {
const token = [Link]?.split(' ')[1];
const decoded = [Link](token, [Link].JWT_SECRET);
[Link] = [Link];
next();
};

■ 3.5 Error Handling and Logging


• try-catch: Wrap async code in try-catch to handle errors gracefully.
• async/await: Modern syntax for handling asynchronous operations. Use with try-catch for error handling.
• HTTP Status Codes: 200 OK, 201 Created, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not
Found, 500 Internal Server Error
• Morgan: HTTP request logger middleware. npm install morgan. Formats: combined, common, dev, short.
• Winston: Advanced logging library with log levels (error, warn, info, debug) and transport options (file,
console).
• dotenv: Load environment variables from .env file. Never commit .env to git.

MEAN Stack Study Notes | Page 10


★ EXAM TIPS:
• [Link] is non-blocking and event-driven – it uses the event loop for concurrency.
• Express middleware signature: (req, res, next) – always call next() unless sending response.
• JWT = JSON Web Token – stateless auth. Format: [Link] (Base64 encoded).
• bcrypt is used to hash passwords. Salt rounds = 10 is standard.
• HTTP methods: GET (read), POST (create), PUT (update/replace), PATCH (partial update), DELETE.
• [Link] (route params), [Link] (query string), [Link] (request body).
• Error handling middleware has 4 parameters: (err, req, res, next).

MEAN Stack Study Notes | Page 11


apter 4: Angular Weightage: 30% | Teaching Ho

■ 4.1 Introduction to Angular


Angular is a TypeScript-based open-source frontend web application framework developed by Google. It is used
to build Single Page Applications (SPAs) and follows the component-based architecture.

• TypeScript: Angular is written in TypeScript – a superset of JavaScript with static typing, interfaces, and
decorators.
• Component-Based: UI is broken into reusable components. Each component = Template (HTML) + Logic
(TS) + Style (CSS).
• Two-Way Data Binding: Automatic synchronization between model and view using [(ngModel)].
• Dependency Injection (DI): Angular's DI system automatically provides services where needed.
• Angular CLI: Command-line interface tool for creating, building, testing Angular apps.
• Modules: Angular apps are organized into NgModules. Root module = AppModule.

Angular vs React vs Vue


Feature Angular React Vue

Type Full Framework Library Progressive Framework

Language TypeScript JavaScript/JSX JavaScript

Data Binding Two-way One-way Two-way

By Google Facebook/Meta Community

Learning Curve Steep Moderate Easy

■ 4.2 Setting Up an Angular Application


# Install Angular CLI globally
npm install -g @angular/cli

# Create new Angular project


ng new my-app

# Navigate to project
cd my-app

# Start development server


ng serve # Runs on [Link]
ng serve --open # Opens browser automatically

# Generate components, services, etc.


ng generate component my-component # or: ng g c my-component
ng generate service my-service # or: ng g s my-service
ng generate module my-module # or: ng g m my-module

# Build for production


ng build --prod

Angular Project Structure


• src/app/ – Main application folder (components, services, modules):
• [Link] – Root module (AppModule) – declares components, imports modules:

MEAN Stack Study Notes | Page 12


• [Link] – Root component:
• [Link] – Angular workspace configuration (build options, assets):
• [Link] – Project dependencies:
• [Link] – TypeScript compiler configuration:

■ 4.3 Components, Modules, and Services

Components
A component controls a view (template). It consists of: HTML template, TypeScript class, CSS styles, and
metadata (decorator).

// [Link]
import { Component } from '@angular/core';

@Component({
selector: 'app-root', // Custom HTML tag
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class AppComponent {
title = 'My App';
students = ['Alice', 'Bob', 'Charlie'];

greet(name: string): string {


return `Hello, ${name}!`;
}
}

Modules (NgModule)
// [Link]
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'; // For ngModel
import { HttpClientModule } from '@angular/common/http'; // For HTTP

@NgModule({
declarations: [AppComponent, HomeComponent], // Components
imports: [BrowserModule, FormsModule, HttpClientModule],
providers: [UserService], // Services
bootstrap: [AppComponent] // Root component
})
export class AppModule { }

Services
Services contain business logic and data that can be shared across components via Dependency Injection (DI).
// [Link]
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({ providedIn: 'root' }) // Singleton – available app-wide


export class UserService {
private apiUrl = '[Link]

constructor(private http: HttpClient) {}

MEAN Stack Study Notes | Page 13


getUsers(): Observable<any[]> {
return [Link]<any[]>([Link]);
}
}

■ 4.4 Data Binding and Templates


Binding Type Syntax Direction Example

Interpolation {{ expression }} Component → View {{ title }}, {{ 2+2 }}

Property Binding [property]="value" Component → View [src]="imageUrl"

Event Binding (event)="handler()" View → Component (click)="onClick()"

Two-Way Binding [(ngModel)]="property" Both directions [(ngModel)]="username"

Structural Directives
<!-- *ngIf – Conditional rendering -->
<div *ngIf='isLoggedIn'>Welcome!</div>
<div *ngIf='age >= 18; else minor'>Adult</div>
<ng-template #minor>Minor</ng-template>

<!-- *ngFor – Loop through list -->


<ul>
<li *ngFor='let student of students; let i = index'>
{{ i+1 }}. {{ [Link] }}
</li>
</ul>

<!-- *ngSwitch – Switch case -->


<div [ngSwitch]='role'>
<p *ngSwitchCase="'admin'">Admin Panel</p>
<p *ngSwitchCase="'user'">User Dashboard</p>
<p *ngSwitchDefault>Guest</p>
</div>

Attribute Directives
• [ngClass]: Dynamically add/remove CSS classes. [ngClass]="{'active': isActive, 'error': hasError}"
• [ngStyle]: Dynamically set inline styles. [ngStyle]="{'color': textColor, 'font-size': fontSize + 'px'}"

■ 4.5 Forms and Validation


Angular provides two approaches for handling forms:

Template-Driven Forms
• Use FormsModule from @angular/forms
• Defined in HTML template using ngModel, ngForm directives
• Simple and easy – best for small forms
• Two-way data binding with [(ngModel)]
<form #loginForm='ngForm' (ngSubmit)='onSubmit(loginForm)'>
<input type='text' name='username'
[(ngModel)]='[Link]'
required minlength='3'
#username='ngModel'>
<div *ngIf='[Link] && [Link]'>

MEAN Stack Study Notes | Page 14


<span *ngIf='[Link]?.required'>Username required!</span>
<span *ngIf='[Link]?.minlength'>Min 3 chars!</span>
</div>
<button type='submit' [disabled]='[Link]'>Login</button>
</form>

Reactive Forms
• Use ReactiveFormsModule from @angular/forms
• Defined programmatically in TypeScript using FormGroup, FormControl, FormBuilder
• More powerful – best for complex forms with dynamic validation
• Validators: [Link], [Link], [Link](n), [Link](regex)
// TypeScript
import { FormBuilder, Validators } from '@angular/forms';

loginForm = [Link]({
email: ['', [[Link], [Link]]],
password: ['', [[Link], [Link](8)]]
});

onSubmit() {
if ([Link]) {
[Link]([Link]);
}
}

■ 4.6 Routing and Navigation


// [Link]
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [


{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'students', component: StudentsComponent },
{ path: 'students/:id', component: StudentDetailComponent },
{ path: '**', component: NotFoundComponent } // Wildcard route
];

// In HTML template
// <router-outlet></router-outlet> – Where components render
// <a routerLink='/home' routerLinkActive='active'>Home</a>

// Programmatic navigation
constructor(private router: Router) {}
[Link](['/students', studentId]);

Route Guards
• CanActivate: Prevents unauthorized access to routes. Used for auth protection.
• CanDeactivate: Prevents user from leaving a route (unsaved changes warning).
• Resolve: Pre-loads data before navigating to a route.
• CanLoad: Prevents lazy-loaded module from loading if not authorized.

■ 4.7 HTTP Client and Observables (RxJS)

MEAN Stack Study Notes | Page 15


Angular uses HttpClientModule to make HTTP requests. Responses are returned as Observables (from RxJS
library).

// Component using a service


export class StudentsComponent implements OnInit {
students: any[] = [];

constructor(private studentService: StudentService) {}

ngOnInit(): void {
[Link]().subscribe({
next: (data) => [Link] = data,
error: (err) => [Link](err),
complete: () => [Link]('Done')
});
}
}

Key RxJS Operators


Term / Concept Explanation

map Transform emitted values Convert API response format

filter Filter values by condition Get specific items

switchMap Cancel previous, switch to new Observable Search with API calls

mergeMap Merge multiple Observables Parallel HTTP requests

catchError Handle errors gracefully Error handling in HTTP

tap Side effects without modifying stream Logging

debounceTime Delay emissions Search input debounce

distinctUntilChanged Skip duplicate consecutive values Avoid duplicate API calls

■ 4.8 Component Lifecycle Hooks


Hook Called When

ngOnChanges Input properties change

ngOnInit Component initialized (after first ngOnChanges) – MOST USED

ngDoCheck Every change detection cycle

ngAfterContentInit Content projected via ng-content initialized

ngAfterContentChecked After every check of projected content

ngAfterViewInit Component view and child views initialized

ngAfterViewChecked After every check of component view

ngOnDestroy Just before component is destroyed – cleanup (unsubscribe)

MEAN Stack Study Notes | Page 16


★ EXAM TIPS:
• Angular uses TypeScript. Decorators: @Component, @NgModule, @Injectable, @Input, @Output.
• Data binding: {{ }} interpolation, [property] property, (event) event, [(ngModel)] two-way.
• Structural directives: *ngIf (conditional), *ngFor (loop), *ngSwitch (switch).
• Template-Driven Forms use FormsModule + ngModel. Reactive Forms use ReactiveFormsModule +
FormBuilder.
• Routing: Routes array, , routerLink, CanActivate guard for protected routes.
• ngOnInit is the most important lifecycle hook – used to fetch data on component load.
• Services use @Injectable({providedIn: 'root'}) for singleton scope across the entire app.
• HttpClient methods: get(), post(), put(), delete() – all return Observables.

MEAN Stack Study Notes | Page 17


pter 5: Integration Weightage: 10% | Teaching H

■ 5.1 Integrating Angular Frontend with [Link] API


The MEAN stack integration connects the Angular frontend to the [Link]/[Link] backend via HTTP REST
APIs, with MongoDB as the database.

CORS – Cross-Origin Resource Sharing


When Angular (localhost:4200) calls Express API (localhost:3000), the browser blocks the request due to CORS
policy. Solution: enable CORS on the backend.
// Backend: Enable CORS
npm install cors

const cors = require('cors');


[Link](cors({
origin: '[Link] // Allow Angular dev server
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization']
}));

Connecting to MongoDB with Mongoose


Mongoose is an ODM (Object Document Mapper) for MongoDB. It provides schema validation and a cleaner
API.
npm install mongoose

// [Link] – Connect to MongoDB


const mongoose = require('mongoose');
[Link]('mongodb://localhost:27017/meanapp')
.then(() => [Link]('MongoDB connected'))
.catch(err => [Link]('Connection error:', err));

// Define Schema + Model


const studentSchema = new [Link]({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
grade: { type: String, enum: ['A','B','C','D','F'] },
createdAt: { type: Date, default: [Link] }
});

const Student = [Link]('Student', studentSchema);

Full CRUD API with Mongoose


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

// POST – create student


[Link]('/api/students', async (req, res) => {
const student = new Student([Link]);
await [Link]();
[Link](201).json(student);

MEAN Stack Study Notes | Page 18


});

// PUT – update student


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

// DELETE – remove student


[Link]('/api/students/:id', async (req, res) => {
await [Link]([Link]);
[Link]({ message: 'Student deleted' });
});

■ 5.2 Authentication & User Management Integration

Complete Auth Flow – MEAN Stack


• User submits login form in Angular → Angular sends POST /api/auth/login
• Express backend checks credentials against MongoDB → generates JWT token
• Angular stores JWT in localStorage or sessionStorage
• Subsequent API calls include token in Authorization header: Bearer
• Express AuthMiddleware verifies token before processing protected routes
• Angular HTTP Interceptors automatically attach JWT to every HTTP request
// Angular HTTP Interceptor – auto-attach JWT
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
const token = [Link]('token');
if (token) {
req = [Link]({
setHeaders: { Authorization: `Bearer ${token}` }
});
}
return [Link](req);
}
}

■ 5.3 Handling Real-Time Data with WebSockets


WebSockets provide full-duplex (bi-directional) communication between client and server over a single
persistent connection. Unlike HTTP (request-response), WebSockets allow the server to push data to clients.

• [Link]: Most popular library for WebSocket implementation. Works with [Link] (server) and browser
(client). Falls back to HTTP long-polling if WebSockets not supported.
• Use Cases: Real-time chat, live notifications, collaborative editing, live dashboards, multiplayer games.
• Events: Custom events: [Link]('event-name', data) to send, [Link]('event-name', callback) to
receive.
// Backend – [Link] setup
const { Server } = require('[Link]');
const io = new Server(server, { cors: { origin: '*' } });

[Link]('connection', (socket) => {

MEAN Stack Study Notes | Page 19


[Link]('User connected:', [Link]);
[Link]('chat-message', (msg) => {
[Link]('chat-message', msg); // Broadcast to all
});
[Link]('disconnect', () => [Link]('User disconnected'));
});

■ 5.4 Error Handling and Testing


• Jasmine: Testing framework used by Angular. Describe blocks and 'it' specs.
• Karma: Test runner that runs Jasmine tests in a browser. Default with Angular CLI.
• ng test: Runs unit tests using Karma + Jasmine.
• Postman: API testing tool – send HTTP requests and validate responses.
• Jest: Alternative JavaScript testing framework. Faster than Karma for unit tests.
• Angular ErrorHandler: Global error handling by extending ErrorHandler class.

★ EXAM TIPS:
• CORS must be enabled on backend when Angular (4200) calls Express (3000).
• Mongoose is an ODM for MongoDB – provides Schema, Model, validation.
• JWT stored in localStorage; sent as 'Authorization: Bearer ' header.
• Angular HTTP Interceptors automatically add token to every outgoing request.
• WebSockets = bi-directional, persistent connection. [Link] is the popular library.
• ng test runs Jasmine unit tests via Karma test runner.

MEAN Stack Study Notes | Page 20


loyment and Best Practices Weightage: 6% | Teaching Ho

■ 6.1 Preparing Application for Deployment


• Angular Production Build: ng build --configuration=production → creates optimized files in /dist folder.
Enables: AoT compilation, tree-shaking, minification, uglification.
• Environment Files: src/environments/[Link] (dev) and [Link] (prod). Store API
URLs and feature flags.
• AoT (Ahead-of-Time) Compilation: Templates compiled at build time → faster startup, smaller bundle.
• Lazy Loading: Load Angular modules on demand → reduces initial load time. loadChildren in routes.
• .env file: Store sensitive configs (DB URL, JWT secret, API keys). Use dotenv package. Never commit to
git.

■ 6.2 Hosting and Server Setup Options


Platform What to Host Notes

Heroku [Link] Backend PaaS, free tier available, easy deployment

Railway / Render [Link] Backend Modern PaaS, auto-deploy from GitHub

Vercel / Netlify Angular Frontend CDN-based static hosting, CI/CD integration

AWS EC2 Full Stack IaaS, full control, requires manual setup

MongoDB Atlas MongoDB Database Cloud MongoDB service, free M0 tier

Firebase Hosting Angular Frontend Google's hosting platform with CDN

DigitalOcean Full Stack VPS hosting, affordable

Nginx Reverse Proxy Serve Angular static files + proxy API requests

■ 6.3 Security Best Practices


• HTTPS / SSL: Always use HTTPS in production. Get free SSL from Let's Encrypt.
• [Link]: Sets security-related HTTP headers automatically. npm install helmet; [Link](helmet()).
• Input Validation: Validate and sanitize all user input on the backend. Use libraries like Joi or
express-validator.
• SQL/NoSQL Injection: Use parameterized queries / Mongoose models to prevent injection attacks.
• Rate Limiting: Limit API requests per IP to prevent brute-force attacks. Use express-rate-limit.
• Password Hashing: Always hash passwords with bcrypt before storing. Never store plain text.
• JWT Best Practices: Short expiry times, use refresh tokens, store securely (httpOnly cookies preferred
over localStorage).
• CORS Policy: Restrict CORS to known origins only.
• Environment Variables: Never hardcode secrets. Use .env files and [Link].

■ 6.4 Performance Optimization and Testing

Frontend (Angular) Optimization


• Lazy Loading modules – load only when needed
• OnPush Change Detection Strategy – reduces unnecessary re-renders
• trackBy in *ngFor – improves list rendering performance

MEAN Stack Study Notes | Page 21


• Caching HTTP responses with HttpClient
• Bundle analysis: ng build --stats-json + webpack-bundle-analyzer

Backend ([Link]) Optimization


• Use clustering or PM2 for multi-core utilization
• Cache responses with Redis
• Use indexes in MongoDB for query optimization
• Compression middleware (gzip): npm install compression; [Link](compression())
• Pagination – limit data returned per request

■ 6.5 Version Control and Continuous Integration


• Git Workflow: git init, git add, git commit, git push. Use .gitignore to exclude node_modules, .env, dist.
• GitHub / GitLab / Bitbucket: Remote repositories for code hosting and collaboration.
• Branching: main/master (production), develop (dev), feature/xxx (feature branches).
• CI/CD: Continuous Integration / Continuous Deployment. Automate testing and deployment.
• GitHub Actions: CI/CD tool integrated with GitHub. Define workflows in .yml files.
• PM2: [Link] process manager. Keeps app running, auto-restart on crash. pm2 start [Link]

★ EXAM TIPS:
• ng build --configuration=production → creates optimized Angular bundle in /dist.
• MongoDB Atlas is the cloud-hosted MongoDB service for production.
• [Link] adds security headers. HTTPS uses SSL/TLS certificates.
• bcrypt hashes passwords. JWT should use httpOnly cookies in production.
• PM2 is the [Link] process manager for production deployments.
• Lazy loading reduces initial Angular bundle size – use loadChildren in routes.
• Git: always add node_modules and .env to .gitignore.

MEAN Stack Study Notes | Page 22


ter 7: Final Project Weightage: 10% | Teaching H

■ 7.1 Project Overview – Full MEAN Stack Application


The final project integrates all components of the MEAN stack into a complete, functional web application. A
typical project is a Student Management System or Blog/E-Commerce application.

Project Architecture – MEAN Stack Flow


+------------------+ HTTP/REST +---------------------+
| Angular (4200) | <--------------------> | [Link] (3000) |
| Frontend SPA | JSON Data | REST API Backend |
+------------------+ +---------------------+
Components |
Services | Mongoose ODM
Routing |
Forms +---------+---------+
HTTP Interceptors | MongoDB (27017) |
| Database |
+-------------------+

■ 7.2 Project Structure

Backend Structure ([Link] + Express)


backend/
■■■ [Link] # Entry point
■■■ config/
■ ■■■ [Link] # MongoDB connection
■■■ models/
■ ■■■ [Link] # Mongoose schemas
■ ■■■ [Link]
■■■ routes/
■ ■■■ [Link] # /api/auth
■ ■■■ [Link] # /api/students
■■■ controllers/
■ ■■■ [Link]
■ ■■■ [Link]
■■■ middleware/
■ ■■■ [Link] # JWT verification
■■■ .env # Environment variables

Frontend Structure (Angular)


frontend/src/app/
■■■ components/
■ ■■■ home/
■ ■■■ login/
■ ■■■ students/
■ ■■■ student-list/
■ ■■■ student-form/
■ ■■■ student-detail/
■■■ services/
■ ■■■ [Link]
■ ■■■ [Link]
■■■ guards/
■ ■■■ [Link]

MEAN Stack Study Notes | Page 23


■■■ interceptors/
■ ■■■ [Link]
■■■ models/
■ ■■■ [Link]
■■■ [Link]

■ 7.3 Key Features to Implement


Feature Technology Used

User Registration & Login Angular Forms + Express API + bcrypt + JWT

JWT Authentication jsonwebtoken + Angular HTTP Interceptor + Route Guard

CRUD Operations Angular + HttpClient + Express + Mongoose + MongoDB

Form Validation Angular Reactive Forms + Validators

Protected Routes Angular CanActivate Guard + JWT verification

Error Handling Express error middleware + Angular catchError

Responsive UI Angular + Bootstrap / Angular Material

Environment Config .env (backend) + [Link] (frontend)

■ 7.4 Quick Reference – Essential Commands


Command Description

npm init -y Initialize new [Link] project

Installbcrypt
npm install express mongoose cors dotenv jsonwebtoken backend dependencies

node [Link] / nodemon [Link] Start backend server

ng new app-name Create new Angular project

ng generate component name Create new component

ng generate service name Create new service

ng serve Start Angular dev server (port 4200)

ng build --configuration=production Build Angular for production

mongosh Open MongoDB shell

[Link]() Query all documents

pm2 start [Link] Start [Link] app with PM2

★ EXAM TIPS:
• Final project should demonstrate: full CRUD, JWT auth, Angular routing, form validation, MongoDB.
• Use MVC pattern on backend: Models (Mongoose), Views (not used in API), Controllers (logic), Routes.
• Separation of concerns: keep business logic in controllers/services, not in route handlers.
• Always use async/await with try-catch for all database operations.
• Test your API with Postman before connecting to Angular frontend.

MEAN Stack Study Notes | Page 24


SION SHEET – All Chapters Weightage: 100% | Teaching H

Ch Topic Key Points to Remember

1 MEAN Stack Intro MEAN = MongoDB+Express+Angular+Node; SPA; HTTP methods; npm; ng new; ng serve

2 MongoDB NoSQL; BSON; CRUD: insertOne/findOne/updateOne/deleteOne; $gt/$lt/$in; Indexes; Aggregation

3 [Link] & Express Non-blocking I/O; Event loop; require/[Link]; [Link]/post/put/delete; Middleware (req,res

4 Angular @Component @NgModule @Injectable; Data binding {{ }},[],(),[()] ; *ngIf *ngFor; Forms; RouterMod

5 Integration CORS; Mongoose ODM; HTTP Interceptor for JWT; [Link] for WebSockets; Jasmine/Karma tes

6 Deployment ng build --prod; Heroku/Vercel/AWS; MongoDB Atlas; [Link]; bcrypt; PM2; GitHub Actions CI/CD

7 Final Project MVC architecture; CRUD API; JWT auth flow; Angular routing + guards; Reactive forms; Error hand

Best of Luck for your Exams!


Study smart: understand concepts, practice code, revise this sheet before exam.

MEAN Stack Study Notes | Page 25

You might also like