Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

JavaScript & Nodejs & MongoDB & Express

The document provides a comprehensive overview of backend development with a focus on Node.js, covering its architecture, modules, file handling, server creation, middleware, error handling, and database connectivity, particularly with MongoDB. It also discusses the role of JWT for secure communication, logging with Winston, centralized error handling, debugging techniques, and the implementation of Role-Based Access Control (RBAC). Additionally, it includes practical steps for setting up Node.js and MongoDB, as well as CRUD operations and API testing.

Uploaded by

2303051057071
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

JavaScript & Nodejs & MongoDB & Express

The document provides a comprehensive overview of backend development with a focus on Node.js, covering its architecture, modules, file handling, server creation, middleware, error handling, and database connectivity, particularly with MongoDB. It also discusses the role of JWT for secure communication, logging with Winston, centralized error handling, debugging techniques, and the implementation of Role-Based Access Control (RBAC). Additionally, it includes practical steps for setting up Node.js and MongoDB, as well as CRUD operations and API testing.

Uploaded by

2303051057071
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

Subtopics to Prepare

1. Introduction to Backend Development


- What is Backend? - Client-Server Architecture

2. Node.js Basics
- Event-driven architecture -Non-blocking I/O - Installation and setup

3. Modules in Node.js
- Built-in modules (fs, http, path, os) - Import/export (CommonJS vs ES Modules)

4. File System & Streams


- Reading and writing files - Working with streams

5. Server Creation
- Using HTTP module - Handling requests and responses

6. Middleware Concepts
- Role of middleware in Node.js

7. Error Handling
- Synchronous and asynchronous

8. Database Connectivity
Node.js
• Node.js is an open-source , cross-platform JavaScript runtime environment.

• It allows developers to Run JavaScript code on the server side, enabling server-side scripting.

• Features of Node.js:

• Asynchronous & Event Driven: Emphasizes non-block , event-driven architecture making it


efficient for handling concurrent operations.

• Single Threaded : Utilizes a single threaded event loop for handling multiple connections
without the need for multi-threading.

• Built on V8 Engine : Powered by the JavaScript Engine from Google Chrome for high
performance.
Event-driven architecture
• Event Driven Architecture is a paradigm in which the flow of the program is determined
by events such as user actions(mouse clicks),or messages from other programs.

• In the context to node.js application, the Events are used to distribute data btw
application or handle the Inter process Communication within the same application.

• Three key concepts are:


• Event Emitter (Producer/publisher): An event emitter emits named event that occurred
in the application.
• Event Listener (Consumer/Subscriber):Event Listener is a function that listens to the
particular events.
• Event Handler : A callback function is tasked to handing the events triggered by the
EventListener.
Event-driven architecture
Program of event driven arc:
Installation and setup
1. Download & Install
(i)Download the Node.js installer from the official website(http://nodejs.org).
(ii)Run the installer and follow the instruction.
2. Verify Installation:
(i) Open your terminal/command prompt
(ii) Type node –v and npm –v to check version.
3. Create a Project
(i)Make a new directory for your project(e.g: mkdir my_project)
(ii)Navigate the directory (cd my_project)
4. Initialize(Op)
Run npm init or npm init –y to create package.js file.
5. Install Dependencies:
Use npm install <package-name> to install necessary packages (e.g., npm install express).
6. Create JavaScript File:
Create a file (e.g., index.js) to write your Node.js code.
7. Run Your Code:
Execute node index.js in the terminal.
Reading and writing files-Working with
streams
Modules
• Modules in node.js are like javascript libraries a set of functions that you can
include in our application.

• Core Modules:
Core modules are already built-in modules or preloaded functions that expose
node core functionality.
1.fs: Interacts with the file system (reading, writing files).
2.HTTP: Creates HTTP servers and handles client requests and response
3.path: Handles file paths.
4.os: Provides operating system-related utility methods.
5.events: Enables event-driven programming
Modules
• Local Modules:
Unlike built-in and external modules, local modules are created locally in your
Node.js application

• Third-party modules:
Third-party modules are modules that are available online using the
Node Package Manager(NPM).
Import/export (CommonJS vs ES
Modules)
Role of middleware
• Middleware refer to function that have access to the handle the request (req)
object and the response (res) object and the next middleware in the chain.

• Role: Types:

Request Handling Application Level


Router Level
Layered Processing
Built-in
Response Sending
Error Handling
Parsing
Method Specific
Error Handling
Third party
Static File Serving
Multiple Callback
Authentication
JavaScript & Node.js
• Execution context
1. Memory Phase – Even before the code start getting executed memory is allocated to
variables function which is also called Variable Environment
2. Code Phase – code is executed line by line it is single threaded everything synchronously
which is also called thread of execution
• Primitive /value type: String ,number,Boolean,underdefined,null,symbol
• Primitive /value type • Number • boolean • underdefined
• String let x=10; or let x=1.4; Let y = true; let x;
let x=“dhyani”; console.log(x); console.log(x); console.log(x);
console.log(x); console.log(typeof(x)); console.log(typeof(x)); console.log(typeof(x)
console.log(typeof(x));// output // output );
// output 10 true // output
dhyani number boolean undefined
string
Reference type
• Reference type: Objects,Array,Function
• Objects:
let course= {
title:”dsa”
des:”project”
}
Console.log(course);//op: { title: “dsa des:”project”}
Console.log(typeof(course))//object
console.log(course.title);
Array
• Array:
Node Package Manager (npm)
• npm:
npm is the default package manager for node.js.
It allow you to install, share & ,manage dependencies in your project.

• Common npm Commands:


Initialize a Project: npm initI
Install a Package: npm install package-name
Install a Package Globally: npm install -g package-name
Update a Package: npm update package-name
Build a simple API using node.js
and Express.js 1
Build a simple API using node.js
and Express.js2
Put data from one file to
another
Handling Requests and
Responses
Handling HTTP Requests and
Responses
Handling HTTP Requests and
Responses
Handling HTTP Requests and
Responses
MongoDB
• MongoDB is one of the well known open source NoSQL database management
system that is classified as document oriented database.
• MongoDB stores data in flexible and dynamic documents that resemble JSON,
using a document-oriented data model.

• Key features :
• Document-Oriented • Open-Source
• NoSQL • Replication & high availability
• Scalability
• Indexes
• Aggregation Framework
MongoDB Collection &
• Collection :
Document
A collection is a group of documents in the database.
A collection named "users" could contain documents representing individual users
with varying information like name, email, age, etc.

• Document:
A document is a single unit of data within a collection.
Represented as a JSON-like structure with key-value pairs.
Setting up MongoDB
Step 1 : Download Mongodb
Go to official website and download(https://www.mongodb.com/try/download/community)
Choose the latest stable version of MongoDB Community Server.
Select Windows as your operating system
Download the MSI installer package.

Step 2 : Install Mongodb


Run the Installer: Double-click the downloaded MSI file.
Follow the Instructions: Follow the on-screen instructions in the installation wizard

Step 3 : Verify Installation


Start MongoDB Service
Connect to MongoDB Shell:
Open a command prompt
Navigate to the MongoDB installation directory (e.g., C:\Program Files\MongoDB\Server\4.4\bin)
Run the mongo command in the command prompt.
If the connection is successful, you will see the MongoDB shell prompt
MongoDB
• NoSQL database referred to “Not Only SQL” database , are a type of database management
system that provides a non-tabular storage mechanism for data.

• Needs or features of NoSQL database:


• Document based • Disadvantages of NoSQL
• Key value based database:
• Flexibility in data model
• Horizontal Scalability • Lack of ACID Transaction
• Support complex data • Learning Curve
• Handling Big data • Lack of Standardization
• High performance
• Distributed & fault tolerant architectures
• Cost effective
MongoDB
• Type of NoSQL Database:

• Documented DB

• Key-value store

• Column Family stores

• Graph Database
MongoDB
• CRUD Operation

CRUD

CRUD
CREATE READ UPDATE DELETE
MongoDB
Create operation
This command help to add new document to the collection.
insertOne() and insertMany() methods to perform insert operation in mongoDB.
• db.collection_name.insertOne(): This Method is useful to insert single
document in Collection.
• db.collection_name.insertMany(): This method is useful to insert many
documents in collection.
MongoDB
Read Operation:
Read operation are used to retrieve data from the database.
For read operation find() is used.
Use db.collection_name.find() method to get all documents from collections.
MongoDB
Filter documents based on a condition:

db.collectionName.find({ key: value }); : Use this command to get the documents
where the value of the field key is equal to the specified value.
MongoDB
Comparison operator:

db.collectionName.find({ age: { $gt: 40 } }); : This will return documents where the
value of the age field is greater than 40.
MongoDB
Count the number of documents:

db.collectionName.find().count(); : This will count how many documents are


present in the collection.
MongoDB
Update Operation:
The update operation is used to modify existing document in a collection.
updateOne():
updateMany(): db.collectionName.updateMany(
{ filter_criteria },
{ $set: { field1: value1, field2: value2, ... } }
);
update():
MongoDB
Delete Operation:

The delete operation is used to remove documents from a collection.


deleteOne(): removes a single document from a collection that matches the
specified filter.
db.collectionName.deleteOne({ filter_criteria });

deleteMany():removes all documents from a collection that match the specified


filter.
db.collectionName.deleteMany({ filter_criteria });
MVC (Model View Controller)
• MVC is a design pattern used in web development for separate concern and
organize code

• Model : represents application data and business logic.


• View : responsible for user interface and presentation of data.
• Controller : act as intermediator btw View and Model.
Client Server communication
• Client Server communication is foundation of web development , where the client
request the resources and the server process those request and response them
back to the client.
• Key concepts:

• HTTP protocols
• Restful
• Web sockets
• GraphQL
• AJAX( asynchronous JavaScript and xml)
JWT(Json Web Tokens)
• JWT is widely used method for stateless communication. It allows secure transaction btw client and server.

How jwt works:


1. User login : 1. The user send credentials (e.g username and password) 2. The server verifies credentials.
2. Jwt structure : JWT structure consists of Payload, Header & Signature.
3. Token generation : Use library like jsonwebtoken to create JWT. const jwt=requirw(“jsonwebtoken”)
const token = jwt.sign({userId:”1234”},”secret key”,{expries :
1h});
4. Token verification : The server verifies the JWT signature and checks its expiration.
jwt.verify(token,”secret-key”,(err,decode)=>{
If(err){
} else{
}
});
5. Client-side storage: 1. Store jwt in client 2. send the token in authorization
Authorization: berear <token>
6. Security consideration : Use HTTPS to prevent token interception
Logging with Winston
• Install Winston: Install Winston using npm: npm install Winston

• Configure transports (e.g., console, file).

• Use log levels: error, warn, info, etc.

• Customize log formats and enable log rotation with winston-daily-rotate-file.

• Log errors in centralized error handling.


Centralized Error Handling
• Middleware for Error Handling: Use middleware in frameworks like Express.js to catch errors globally.
app.use((err, req, res, next) => {
console.error(err.stack); // Log the error
res.status(500).json({ message: "Something went wrong!" });

• Custom Error Classes: Create custom error classes for specific error types (e.g., NotFoundError,
ValidationError).

• Async Error Handling: Use try/catch or libraries like express-async-errors to handle errors in asynchronous
code.
const asyncHandler = (fn) => (req, res, next) => {
promise.resolve(fn(req, res, next)).catch(next);
};

• Global Uncaught Exceptions: Handle uncaught exceptions and unhandled promise rejections at the process
Debugging
• Debugging:
Logging: Use logging libraries like winston or morgan to track application behavior.
const logger = require("winston");
logger.error("Error message");
logger.info("Info message");

Debugging Tools: Use console.log or debugger statements for quick debugging.


Use Node.js debugging tools like node-inspect or IDE integrations.

Error Stack Traces : Analyze stack traces to identify the source of errors.
Use source maps for debugging minified or transpiled code.

API Testing: Use tools like Postman or Insomnia to test API endpoints
Role-Based Access Control (RBAC)
• RBAC is a security model that restricts system access based on user roles. Here's a quick overview:
• Roles: Define roles (e.g., Admin, Editor, Viewer) based on job functions.

• Permissions: Assign specific permissions to roles (e.g., read, write, delete).

• Users: Assign roles to users (e.g., User1 = Admin, User2 = Editor).

• Access Control: Check user roles and permissions before granting access to resources.
How It Works
• Define Roles: Create roles and assign permissions.

• Assign Roles: Assign roles to users.

• Check Permissions: Verify if a user's role has the required permission for an action

You might also like