Node Express Mongo Notes
Node Express Mongo Notes
NodeJS
Complete Course
Introduction to NodeJS
1. Pre-requisites
2. What is NodeJS
3. NodeJs Features
4. JavaScript on Client
5. JavaScript on Server
6. Client Code vs Server Code
7. Other uses of NodeJs
8. Server architecture with NodeJs
JS is required for NodeJS
React is recommended before NodeJS
2.What is NodeJS
1. File System Access: Provides APIs to read and write files directly,
which is not possible in browser environments for security
reasons.
2. Server-Side Capabilities: Node.js enables JavaScript to run on the
server, handling HTTP requests, file operations, and other
server-side functionalities.
3. Modules: Organize code into reusable modules using require().
3. NodeJs Features
(Removed)
3. NodeJs Features
4. JavaScript on Client
5. JavaScript on Server
6. Client Code vs Server Code
7. Other uses of NodeJs
8. Server architecture with NodeJs
2. Installation of NodeJS
1. What is IDE
2. Need of IDE
3. MAC Setup
• Install latest Node & VsCode
4. Windows Setup
• Install latest Node & VsCode
5. Linux Setup
• Install latest Node & VsCode
6. VsCode (Extensions and Settings)
7. Executing first .js file
8. What is REPL
9. Executing Code via REPL
2.1 What is IDE
1. IDE stands for Integrated
Development Environment.
2. Software suite that
consolidates basic tools
required for software
development.
3. Central hub for coding,
finding problems, and testing.
4. Designed to improve
developer efficiency.
2.2 Need of IDE
1. Streamlines development.
2. Increases productivity.
3. Simplifies complex tasks.
4. Offers a unified
workspace.
5. IDE Features
1. Code Autocomplete
2. Syntax Highlighting
3. Version Control
4. Error Checking
2.3 MAC Setup
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
2.3 MAC Setup
(Install latest Node)
Search Download NodeJS
2.3 MAC Setup
(Install VsCode)
• Click to edit Master text styles
Search VS Code on Google
• Second level
• Third level
• Fourth level
• Fifth level
2.4 Windows Setup
• Click to edit Master text styles
• Second level
• Third level
• Fourth level
• Fifth level
2.4 Windows Setup
(Install latest Node)
Search Download NodeJS
2.4 Windows Setup
(Install VsCode)
Search
• Click toVS
editCode
Master on
text Google
styles
• Second level
• Third level
• Fourth level
• Fifth level
2.5 Linux Setup
2.5 Linux Setup
(Install latest Node)
Search Download NodeJS
2.5 Linux Setup
(Install VsCode)
Search
• Click toVS
editCode
Master on
text Google
styles
• Second level
• Third level
• Fourth level
• Fifth level
2.6 VsCode
(Extensions and Settings)
1. • Click toisedit
What IDE Master text styles
• Second level
2. Need• Third
of level
IDE
• Fourth level
3. MAC Setup • Fifth level
• Install latest Node & VsCode
4. Windows Setup
• Install latest Node & VsCode
5. Linux Setup
• Install latest Node & VsCode
6. VsCode (Extensions and Settings)
7. Executing first .js file
8. What is REPL
9. Executing Code via REPL
3. First Node Server
1. How DNS Works?
2. How Web Works?
3. What are Protocols?
4. Node Core Modules
5. Require Keyword
6. Creating first Node Server
3.1 How DNS Works?
1. Domain Name Entry: User types a domain (e.g.,
www.example.com) into the browser.
2. DNS Query: The browser sends a DNS query to resolve
the domain into an IP address.
3. DNS Server: Provides the correct IP address for the
domain.
4. Browser Connects: The browser uses the IP to connect
to the web server and loads the website.
3.1 How DNS Actually Works?
1. Root DNS: Acts as the starting point for DNS resolution. It
directs queries to the correct TLD server (e.g., .com, .org).
2. TLD (Top-Level Domain) DNS: Handles queries for specific
top-level domains (e.g., .com, .net) and directs them to the
authoritative DNS server (e.g., Verisign for .com, PIR for .org)
3. Authoritative DNS: Contains the actual IP address of the
domain and answers DNS queries with this information.(e.g.,
Cloudflare, Google DNS).
3.2 How Web Works?
1. Client Request Initiation: The client (browser) initiates a
network call by entering a URL.
2. DNS Resolution: The browser contacts a DNS server to
get the IP address of the domain.
3. TCP Connection: The browser establishes a TCP
connection with the server's IP address.
4. HTTP Request: The browser sends an HTTP request to
the server.
5. Server Processing: The server processes the request and
prepares a response.
6. HTTP Response: The server sends an HTTP response back
to the client.
7. Network Transmission: The response travels back to the
client over the network.
8. Client Receives Response: The browser receives and
interprets the response.
9. Rendering: The browser renders the content of the
response and displays it to the user.
3.3 What are Protocols?
Http (HyperText Transfer Protocol):
● Facilitates communication between a web browser and a server to
transfer web pages.
● Sends data in plain text (no encryption).
● Used for basic website browsing without security.
HTTPS (HyperText Transfer Protocol Secure):
● Secure version of HTTP, encrypts data for secure communication.
● Uses SSL/TLS to encrypt data.
● Used in online banking, e-commerce.
TCP (Transmission Control Protocol):
● Ensures reliable, ordered, and error-checked data delivery over the
internet.
● Establishes a connection before data is transferred.
3.4 Node Core Modules
1. Built-in: Core modules are included
with Node.js installation.
2. No Installation Needed: Directly
available for use without npm
install.
3. Performance: Highly optimized for
performance.
3.4 Node Core Modules
1. fs (File System): Handles file operations like reading and
writing files.
2. http: Creates HTTP servers and makes HTTP requests.
3. https: Launch a SSL Server.
4. path: Provides utilities for handling and transforming file
5. paths.os: Provides operating system-related utility methods
and properties.
6. events: Handles events and event-driven programming.
7. crypto: Provides cryptographic functionalities like hashing and
encryption.
8. url: Parses and formats URL strings.
3.5 Require Keyword
1. Purpose: Imports modules in Node.js. Syntax:
2. Caching: Modules are cached after the const moduleName = require('module’);
first require call.
3. .js is added automatically and is not
needed to at the end of module name.
4. Path Resolution: Node.js searches for
modules in core, node_modules, and file
paths.
3.6 Creating first Node Server
3.6 Creating first Node Server
3.6 Creating first Node Server
node app.js
3.6 Creating first Node Server
3.6 Creating first Node Server
Revision
• Click to edit Master text styles
1. How
• SecondDNSlevel
• Third level
Works?
2. How Web Works?
• Fourth level
• Fifth level
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers
4.3 Understand Request Object
1. Streams
2. Chunks
3. Buffers
4. Reading Chunk
5. Buffering Chunks
6. Parsing Request
7. Using Modules
5.1 Streams
5.1 Streams
5.2 Chunks
5.2 Chunks
5.3 Buffers
5.4 Reading Chunk
5.5 Buffering Chunks
5.6 Parsing Request
5.6 Parsing Request
5.7 Using Modules
5.7 Using Modules
Practise Set
Create a Calculator
1. Create a new Node.js project named “Calculator”.
2. On the home page (route “/”), show a welcome message and a
link to the calculator page.
3. On the “/calculator” page, display a form with two input fields
and a “Sum” button.
4. When the user clicks the “Sum” button, they should be taken to
the “/calculate-result” page, which shows the sum of the two
numbers.
○ Make sure the request goes to the server.
○ Create a separate module for the addition function.
○ Create another module to handle incoming requests.
○ On the “/calculate-result” page, parse the user input, use
the addition module to calculate the sum, and display the
result on a new HTML page.
Revision
• Click to edit Master text styles
1. Streams
• Second level
• Third level
3. Buffers
4. Reading Chunk
5. Buffering Chunks
6. Parsing Request
7. Using Modules
6. Event Loop
1. Event Driven
2. Single Threaded
3. V8 vs libuv
4. Node Runtime
5. Event Loop
6. Async Code
7. Blocking Code
6.1 Event Driven
6.2 Single Threaded
6.3 V8 vs libuv
V8:
1. Open-source JavaScript engine by Google.
2. Used in Chrome and Node.js.
3. Compiles JavaScript to native machine
code.
4. Ensures high-performance JavaScript
execution.
libuv:
1. Multi-platform support library for Node.js.
2. Handles asynchronous I/O operations.
3. Provides event-driven architecture.
4. Manages file system, networking, and
timers non-blockingly across platforms.
6.4 Node Runtime
6.4 Node Runtime
6.4 Node Runtime
6.4 Node Runtime
6.5 Event Loop
● timers: this phase executes callbacks
scheduled by setTimeout() and
setInterval().
● pending callbacks: executes I/O callbacks
deferred to the next loop iteration.
● idle, prepare: only used internally.
● poll: retrieve new I/O events; execute I/O
related callbacks (almost all with the exception
of close callbacks, the ones scheduled by
timers, and setImmediate()); node will
block here when appropriate.
● check: setImmediate() callbacks are
invoked here.
● close callbacks: some close callbacks, e.g.
socket.on('close', ...).
6.5 Event Loop
6.6 Async Code
6.6 Async Code
6.7 Blocking Code
6.7 Blocking Code
Run & Observe
Blocking vs Async
const fs = require('fs');
// Timer queue
setTimeout(() => console.log('3. Timer 1'), 0);
// I/O queue
const fs = require('fs');
fs.readFile('user-details.txt', () => console.log('4. I/O operation'));
// Check queue
setImmediate(() => console.log('5. Immediate 1'));
// Close queue
process.on('exit', (code) => {
console.log('6. Exit event');
});
1. • Click
Event to edit Master text styles
• Second levelDriven
• Third level
2. Single Threaded
• Fourth level
• Fifth level
3. V8 vs libuv
4. Node Runtime
5. Event Loop
6. Async Code
7. Blocking Code
7. NPM & Tools
npm install
Recreates node_modules
7.7 Using nodemon
3. npm Scripts
4. npm Packages
5. Installing Packages
6. Installing nodemon
7. Using nodemon
8. Errors & Debugging
1. Types of Errors
2. Syntax Errors
3. Runtime Errors
4. Logical Errors
5. Using the Debugger
6. Debugger with Async Code
7. Restart Debug with nodemon
8.1 Types of Errors
Step 2
8.5 Using the Debugger
Step 4: Use the tools Step 6: Debug Panel
Step 5: Hover
8.5 Using the Debugger
Step 7: Using Debug Console
8.6 Debugger with Async Code
8.7 Restart Debug with nodemon
Practise Set
Debug and fix Syntax, Runtime and Logical Errors
function calculateArea(width, height {
return width + height;
}
2. Syntax Errors
• Fifth level
3. Runtime Errors
4. Logical Errors
5. Using the Debugger
6. Debugger with Async Code
7. Restart Debug with nodemon
9. Starting with Express.js
1. What is Express.js
2. Need of Express.js
3. Installing Express.js
4. Adding Middleware
5. Sending Response
6. Express DeepDive
7. Handling Routes
9.1 What is Express.js
1. Express.js is a minimal and flexible
web application framework for
Node.js.
2. It provides a robust set of features
for building single-page,
multi-page, and hybrid web
applications.
3. Express.js simplifies server-side
coding by providing a layer of
fundamental web application
features.
9.2 Need of Express.js
1. Express.js Simplifies Server Creation: Helps in quickly
setting up and running a web server without the need
for complex coding.
2. Routing Management: Provides a powerful routing
mechanism to handle URLs and HTTP methods
effectively.
3. Middleware Support: Allows the use of middleware to
handle requests, responses, and any middle operations,
making code modular and maintainable.
4. API Development: Facilitates easy and efficient
creation of RESTful APIs.
5. Community and Plugins: Has a large ecosystem with
numerous plugins and extensions, accelerating
development time.
9.3 Installing Express.js
9.3 Installing Express.js
9.4 Adding Middleware
9.4 Adding Middleware
9.4 Adding Middleware
9.5 Sending Response
9.6 Express DeepDive
9.6 Express DeepDive
9.6 Express DeepDive
9.7 Handling Routes
9.7 Handling Routes
1. Order matters
2. Can not call next() after
send()
3. “/” matches everything
4. Calling res.send implicitly
calls res.end()
9.7 Handling Routes
9.7 Handling Routes
Practise Set
2. Need of Express.js
• Fourth level
• Fifth level
3. Installing Express.js
4. Adding Middleware
5. Sending Response
6. Express DeepDive
7. Handling Routes
10. Express.js DeepDive
1. Parsing Requests
2. Express Router
3. Adding 404
4. Common Paths
5. Adding HTML Files
6. Serving HTML Files
7. Using File Helper
10.1 Parsing Requests
10.2 Express Router
10.2 Express Router
10.2 Express Router
10.3 Adding 404
10.4 Common Paths
or
10.5 Adding HTML Files
10.6 Serving HTML Files
10.7 Using File Helper
Practise Set
2. Express Router
• Fourth level
• Fifth level
3. Adding 404
4. Common Paths
5. Adding HTML Files
6. Serving HTML Files
7. Using File Helper
11. Styling using
1. Install:
npm init -y
npm install -D tailwindcss postcss autoprefixer
2. Initialize Tailwind CSS Config
npx tailwindcss init
11.6 Installing Tailwind CSS
Configure Tailwind in the Configuration Files (tailwind.config.js)
11.6 Installing Tailwind CSS
8. Run Command
npm run tailwind
11.7 Using Tailwind CSS
11.8 Building Tailwind Automatically
Practise Set
3. Utility Classes
4. Installing Extension
5. Including Tailwind CSS
6. Installing Tailwind CSS
7. Using Tailwind CSS
12. Dynamic UI using EJS
1. Need of Dynamic UI
2. Sharing using Global Variables
3. What is EJS
4. Installing EJS
5. Using EJS Templates
6. Working with Partials
12.1 Need of Dynamic UI
● Personalized Content: Tailors responses based on user
profiles, preferences, or behaviors to enhance user
experience.
● Dynamic Data Delivery: Provides real-time information
that updates with each request, such as live scores or
stock prices.
● Security and Access Control: Delivers different content
based on user authentication and authorization levels.
● Localization and Internationalization: Adjusts
responses to accommodate different languages, cultures,
or regional settings.
● API Versatility: Supports multiple client types (web,
mobile, IoT) by providing appropriate data formats and
structures.
12.2 Sharing using Global Variables
3. What is EJS
4. Installing EJS
5. Using EJS Templates
6. Working with Partials
13. Model View Controller
1. Separation of Concerns
2. Adding First Controller
3. Adding All Controllers
4. Adding 404 Controller
5. Adding Models
6. Writing data to Files
7. Nodemon causing problems
8. Reading data from Files
13.1 Separation of Concerns
● MVC stands for Model-View-Controller: A
software architectural pattern for developing
user interfaces.
● Model: Manages the data and business logic
of the application.
● View: Handles the display and presentation
of data to the user.
● Controller: Processes user input, interacts
with the Model, and updates the View
accordingly.
● Routes are a part of Controllers.
● Purpose: MVC separates concerns within an
application, making it easier to manage and
scale.
13.2 Adding First Controller
13.3 Adding All Controllers
13.3 Adding All Controllers
13.3 Adding All Controllers
13.4 Adding 404 Controller
13.5 Adding Models
13.5 Adding Models
13.6 Writing data to Files
13.6 Writing data to Files
13.7 Nodemon causing problems
13.8 Reading data from Files
13.8 Reading data from Files
Practise Milestone
1. • Separation
Click to edit Master textof
• Second level
stylesConcerns
2.
3.
14.2 Adding Home Details Page
4.
5.
14.3 Showing Real Home Data
1. Add a static findById method in Home model that takes a callback.
2. Use this findById method in the controller to load home details and log
them.
3. Now change the controller:
a. Redirect to /homes in case the home is not found, logging an error.
b. Rendering the /home-detail page with home data.
4. Create a home-detail page to use the entire page to show all home data.
5. Download from Github:
a. The styled home-detail file.
b. 10 image of homes that you can put locally and use.
14.3 Showing Real Home Data
1.
2.
14.3 Showing Real Home Data
3.
14.3 Showing Real Home Data
4. 5.
14.4 Adding Favourites Feature
1. Create a partial with a form and a button that submits to /favourites path
with a hidden input having home-id value.
2. Add this partial to home-detail page
3. Add this partial to home-list page.
4. Add router for handling POST request to /favourites path.
5. Add a method in store controller to add a home id as favourites, logging
the id for now, before redirecting to /favourites path.
14.4 Adding Favourites Feature
1.
2.
14.4 Adding Favourites Feature
3.
14.4 Adding Favourites Feature
4.
5.
14.5 Adding Favourites Model
1. Create a new Model to handle Favourites:
a. A static method getFavourites that reads the favourites.json file and
return the ids of all homes marked favourite.
b. A static method addFavourites that adds the home-id to favourites-id
array if not already there, then updates the file.
2. Use this model in addFavourites controller.
3. Use this model in getFavourites controller while also fetching details of
all homes from Homes Model.
4. Change the UI of favourites page to show new content.
14.5 Adding Favourites Model
1.
14.5 Adding Favourites Model
2.
14.5 Adding Favourites Model
3.
14.5 Adding Favourites Model
4.
14.6 Edit-Home:
Adding Feature Skeleton
1.
2.
14.7 Edit-Home: Showing Existing Data
3.
14.6 Edit-Home: Adding Feature Skeleton
4.
5.
14.7 Edit-Home:
Showing Existing Data
1. Change the controller to now fetch the home details, if not found
redirect to /host/host-home-list otherwise passing the data to view.
2. Change the edit-home.ejs to show dynamic content based on values:
a. Different submit path.
b. Different button text.
c. Pre-filled values if present.
14.7 Edit-Home: Showing Existing Data
1.
14.7 Edit-Home: Showing Existing Data
2.
14.8 Edit-Home:
Handing Edit Request
1. Add a router for POST /edit-home
2. Add a controller for /edit-home, which creates a home model object
and saves it, before redirecting to /host/host-home-list
3. Add hidden id input field in the edit-home.ejs to get the id as part of
POST request.
4. Change the save method in Model to handle creation of new as well
as updation of existing Home.
14.8 Edit-Home: Handing Edit Request
1.
2.
3.
14.8 Edit-Home: Handing Edit Request
4.
14.9 Adding Delete Feature
1. Surround the delete button with a form that submits to path
/host/delete-home/:homeId
2. Add a route in the host routes.
3. Add a static delete method to the Home model that takes an id and deletes
the home.
4. Add a method in host controller to handle the request, delete the home and
redirect to /host/host-homes-list page.
5. Pending: deleted homes might still be in favourites list.
14.9 Adding Delete Feature
1.
2.
3.
14.9 Adding Delete Feature
4.
14.10 Removing Home from Favourites
1. Add a static method to the favourites model to delete the home.
2. Add a form to the favourites-list in each home to path
/favourites/delete/:homeId
3. Add a route for POST delete-favourites in the store routes.
4. Add a method in store controller to use the model’s static method and then
redirect to favourites-list.
5. Use this model method in home-delete to make sure any deleted home is
also removed from favourites.
14.10 Removing Home from Favourites
1.
2.
3.
14.10 Removing Home from Favourites
4.
5.
Revision
1. • What areMaster
Click to edit dynamic paths
text styles
• Second level
2. Adding Home Details Page
• Third level
1. What is a DB (Database)
2. Introduction to SQL DB
3. Introduction to NoSQL DB
4. SQL vs NoSQL
5. Installing MySQL
6. Connecting App to DB
7. Creating homes Table
8. Querying homes in App
9. Adding DB in Models
10. Adding Home in Model
11. Implementing Model using Where
15.1 What is a DB (Database)
1. Store Data: Keep large amounts of data in a structured format.
2. Enable Data Management: Allow for adding, updating, and deleting
data easily.
3. Facilitate Quick Access: Provide fast retrieval of data through
queries.
4. Ensure Data Integrity: Maintain accuracy and consistency of data
over time.
5. Support Multiple Users: Handle concurrent access by many users
simultaneously.
6. Secure Data: Protect information through access controls and
authentication.
15.2 Introduction to SQL DB
● Vertical Scalability: Typically scaled
by increasing the resources of a single
server (scaling up).
● Relationships: Tables can have
multiple types of relationships.
6.
15.9 Adding DB in Models
7.
15.10 Adding Home in Model
1. Add the description field in home. Change constructor and usage.
2. Make changes in UI to input and show it everywhere.
3. Implement the save method using the insert query.
4. Change the usages of save method to use the promise.
15.10 Adding Home in Model
1.
15.10 Adding Home in Model
2.
15.10 Adding Home in Model
3.
4.
15.11 Implementing Model using Where
Practise Milestone
1. Click to edit
•What is aMaster text styles
DB (Database)
• Second level
2. Introduction
• Third level to SQL DB
• Fourth level
3. Introduction• Fifth level to NoSQL DB
4. SQL vs NoSQL
5. Installing MySQL
6. Connecting App to DB
7. Creating homes Table
8. Querying homes in App
9. Adding DB in Models
10. Adding Home in Model
11. Implementing Model using Where
16. Introduction to MongoDB
1. What is MongoDB
2. Setting up MongoDB
3. Installing MongoDB Driver
4. Creating MongoDB Connection
5. Saving a Home
6. Install MongoDB Compass
7. Install MongoDB for VSCode
8. Fetching all Homes
9. Fetching one Home
10. Supporting Edit & Delete
11. Adding MongoDB to Favourite
16.1 What is MongoDB
1. MongoDB is the product and the company that builds it.
2. The name comes from the work Humongous.
3. NoSQL Document Database: Stores data in flexible, JSON-like
documents.
4. Dynamic Schema: Allows fields to vary across documents without
predefined schemas.
5. High Performance: Optimized for fast read and write operations.
6. Scalability: Supports horizontal scaling through sharding.
7. High Availability: Provides replication with automatic failover.
8. Rich Query Capabilities: Offers powerful querying, indexing, and
aggregation.
9. Geospatial and Text Search: Includes support for location-based
and full-text queries.
10. Cross-Platform Compatibility: Works with various operating
systems and programming languages.
11. Easy Integration: Integrates smoothly with modern development
stacks.
16.2 Setting up MongoDB
VS
16.2 Setting up MongoDB
16.2 Setting up MongoDB
16.2 Setting up MongoDB
16.2 Setting up MongoDB
16.3 Installing MongoDB Driver
16.3 Installing MongoDB Driver
16.3 Installing MongoDB Driver
16.3 Installing MongoDB Driver
16.4 Creating MongoDB Connection
16.5 Saving a Home
16.6 Install MongoDB Compass
16.6 Install MongoDB Compass
16.6 Install MongoDB Compass
16.6 Install MongoDB Compass
16.6 Install MongoDB Compass
16.6 Install MongoDB Compass
16.7 Install MongoDB for VSCode
16.7 Install MongoDB for VSCode
16.7 Install MongoDB for VSCode
16.7 Install MongoDB for VSCode
16.7 Install MongoDB for VSCode
16.8 Fetching all Homes
1. Basic Usage: collection.find(query) retrieves
documents matching the query criteria.
2. Returns a Cursor: The method returns a
cursor, an iterator over the result set.
16.8 Fetching all Homes
16.9 Fetching one Home
16.9 Fetching one Home
16.9 Fetching one Home
16.9 Fetching one Home
16.10 Supporting Edit & Delete
16.11 Adding MongoDB to Favourite
1. Remove all the file handling related code from Favourite Model.
2. Delete the data folder.
3. Change the following methods in Favourite model to use mongo:
a. fetchAll
b. Change addToFavourites to save method
c. deleteById
4. Change the usages of Favourite model in StoreController to use the promise syntax
a. getFavourites
b. postAddFavourites
c. postRemoveFavourite
16.11 Adding MongoDB to Favourite
1. 2.
16.11 Adding MongoDB to Favourite
3.
16.11 Adding MongoDB to Favourite
4.a.
16.11 Adding MongoDB to Favourite
4.b.
16.11 Adding MongoDB to Favourite
4.c.
Practise Milestone
1. What is Mongoose
2. Setting up Mongoose
3. Create Home Schema
4. Saving Home using Mongoose
5. Fetching Homes
6. Fetching one Home
7. Editing a Home
8. Deleting a Home
9. Using Mongoose for Favourite
10. Fetching Relations
17.1 What is Mongoose
1. Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js.
2. Provides a schema-based solution to model application data.
3. Simplifies data validation and type casting in Node.js applications.
4. Enables easy interaction with MongoDB through intuitive methods.
5. Supports middleware for pre and post-processing of data.
6. Helps manage relationships between data with built-in functions.
17.2 Setting up Mongoose
17.2 Setting up Mongoose
1. Install Mongoose package.
2. Import and use mongoose in app.js
3. Delete the database-util file.
4. Remove the usage of db-util from everywhere.
1.
17.2 Setting up Mongoose
2.
17.3 Create Home Schema
1. Delete complete airbnb db from mongo.
2. Delete the existing Home Model code.
3. Create the new Home Schema in the Home Model File.
17.4 Saving Home using Mongoose
17.5 Fetching Homes
17.6 Fetching one Home
1, 2.
17.9 Using Mongoose for Favourite
3.a.
17.9 Using Mongoose for Favourite
3.b.
17.9 Using Mongoose for Favourite
3.c.
17.9 Using Mongoose for Favourite
4.
17.10 Fetching Relations
Revision
1. •What is Master
Click to edit Mongoose
text styles
• Second level
2. Setting
• Third levelup Mongoose
• Fourth level
3. Create Home Schema
• Fifth level
1.
18.2 Adding Login Functionality
2.
18.2 Adding Login Functionality
3.
18.2 Adding Login Functionality
3.
18.2 Adding Login Functionality
4, 5.
18.3 Checking Login State
1. Add a isLoggedIn field in the req object and use it everywhere
else.
2. Add a condition in the navigation ejs file that no path other
than home and login should be visible until a user has logged in.
3. Fix all the render calls to send the flag
4. Also add a middleware for host routes that if the user is not
logged in they should be redirected to the login page.
18.3 Checking Login State
1.
18.3 Checking Login State
2.
18.3 Checking Login State
3.
18.3 Checking Login State
4.
18.4 Using a Cookie
1. Understand why a global variable would not work.
2. Set a cookie on successful login. See it in storage, also on the
next request.
3. Read the cookie using syntax and Define a middleware to set
this value to the request object.
console.log(req.get('Cookie').split('=')[1]);
4. Change the Cookie from the browser and see the result.
18.4 Using a Cookie
2.
3.
18.4 Using a Cookie
4.
18.5 Define the Logout Feature
1. Define a logout button in nav bar that should come only when
user is logged in. Button should be a form that submits to link
/logout.
2. Hide the login button in case user is logged in.
3. Handle the logout path and set the isLoggedIn cookie to false.
18.5 Define the Logout Feature
1, 2.
18.5 Define the Logout Feature
3.
18.6 Problem with Cookies
1. Cookies can be intercepted or stolen, posing
security risks.
2. They have limited storage capacity (about
4KB).
3. Users can delete or modify cookies, leading
to data loss or tampering.
4. Data in cookies is not encrypted, making
sensitive information vulnerable.
5. Storing important info in cookies exposes it
to client-side attacks.
18.7 What are Sessions
3.
4.
18.9 Creating a Sessions
5.
18.10 Saving Session in DB
18.10 Saving Session in DB
Practise Milestone
4. Using a Cookie
5. Define the Logout Feature
6. Problem with Cookies
7. What are Sessions
8. Installing Session Package
9. Creating a Sessions
10. Saving Session in DB
19. Authentication & Authorization
1. What is Authentication
2. What is Authorization
3. Session based Authentication
4. Authentication vs Authorization
5. Signup UI
6. Using Express Validator
7. Adding User Model
8. Encrypting Password
9. Implementing Login
10. Adding User Functions
19.1 What is Authentication
1.
19.5 Signup UI
2.
19.5 Signup UI
3, 4.
19.6 Using Express Validator
1. Add handling for POST /signup in auth controller and router.
2. Install Express Validator.
3. Use the email and password validations in the post handler.
4. Change the signup.ejs to show the errors. And accept the old
values.
19.6 Using Express Validator
1.
2.
19.6 Using Express Validator
3.
19.6 Using Express Validator
3.
19.6 Using Express Validator
4.
19.7 Adding User Model
1. Define a new User Model with following fields:
a. firstName & lastName (required)
b. email (required, unique)
c. Password (required)
d. userType (possible values ‘guest’, ‘host’)
2. In the POST signup handler, create a new user with the fields
from request and redirect to login after saving the user.
19.7 Adding User Model
1.
19.7 Adding User Model
2.
19.8 Encrypting Password
1. Understand the problem with plain text passwords.
2. Install a package named: bcryptjs
3. Hash the password before saving password.
4. Understand that even server does not have the password.
19.8 Encrypting Password
2.
19.8 Encrypting Password
3.
19.9 Implementing Login
1. Read the email and password from the request body and
find the user with the email from the Users collection.
2. If the user is not found send an error and re-render the
login page, also make changes to the login page to show
errors.
3. If the user is found, then use the bcrypt compare function
to match the entered password, If password does not
match send another error, otherwise create a login session
and redirect user to the home.
19.9 Implementing Login
1.
19.9 Implementing Login
2.
19.9 Implementing Login
3.
19.10 Adding User Functions
1. Make the navigation bar items display only on the basis of userType by
passing the user object to all views.
2. Add a field in User Model names favouriteHomes, which is an array of
home ids.
3. Remove the Favourite Model and the Pre hook from the Home Model.
4. Make the favourite user specific and change the following methods:
a. postAddFavourites
b. getFavourites
c. postRemoveFavourite
19.10 Adding User Functions
1.
19.10 Adding User Functions
2.
19.10 Adding User Functions
4.a.
19.10 Adding User Functions
4.b.
19.10 Adding User Functions
4.c.
Revision
1. •What is Master
Click to edit Authentication
text styles
• Second level
2. What is Authorization
• Third level
4. Authentication vs Authorization
5. Signup UI
6. Using Express Validator
7. Adding User Model
8. Encrypting Password
9. Implementing Login
10. Adding User Functions
Practise Milestone
1.
Practise Milestone (Solution)
2.
Practise Milestone (Solution)
3.