JavaScript & Nodejs & MongoDB & Express
JavaScript & Nodejs & MongoDB & Express
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)
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:
• 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.
• 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:
• 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.
• Documented DB
• Key-value store
• 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:
• 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.
• 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");
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.
• Access Control: Check user roles and permissions before granting access to resources.
How It Works
• Define Roles: Create roles and assign permissions.
• Check Permissions: Verify if a user's role has the required permission for an action