Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

Database Introduction in Node.js

Learn what databases are, why applications need them, and how Node.js applications connect to databases to store, retrieve, update, and delete data.

A database is an organized collection of data. Applications use databases to store information such as user details, products, orders, employee records, and customer information.

In Node.js applications, databases help preserve information even after the application is restarted. Instead of keeping all data only in memory, an application can store it in a database and retrieve it whenever required.

Remember: Node.js handles application logic, while the database stores and manages the application's data.

1. What Is a Database?

A database is a place where application data is stored in an organized manner. It allows applications to retrieve, insert, update, and delete information efficiently.

For example, an online shopping application may store product information in a database.

ProductId ProductName Price
1 Laptop 50000
2 Mobile 20000
3 Keyboard 1500

When a user opens the products page, the application retrieves these records from the database and displays them to the user.

2. Why Do Applications Need a Database?

Applications need databases to store and manage information reliably. Without a database or another form of persistent storage, data held only in application memory may be lost when the application restarts.

  • Store user registration and login information.
  • Maintain product and inventory details.
  • Store customer orders and payment records.
  • Retrieve information whenever users request it.
  • Update existing records when information changes.
  • Delete records when they are no longer required.
Example: If an online shopping application stores product details only in a JavaScript array, those changes will generally disappear when the Node.js process restarts. A database provides persistent storage.

3. Types of Databases

Databases can be classified into different types. Two common categories used in Node.js applications are relational databases and NoSQL databases.

Relational Database

A relational database stores data in tables containing rows and columns. SQL is commonly used to query and manipulate the data.

Examples:

  • MySQL
  • PostgreSQL
  • Microsoft SQL Server

NoSQL Database

NoSQL databases use different data models, such as documents or key-value pairs. Document databases can store records in flexible JSON-like structures.

Examples:

  • MongoDB
  • Redis
  • Apache Cassandra

4. SQL vs NoSQL Databases

SQL and NoSQL databases differ in their data models, querying methods, and schema approaches. The right choice depends on the application's needs.

Feature SQL Database NoSQL Database
Data model Tables, rows, and columns Documents, key-value pairs, or other models
Schema Usually defined using tables and column types Depends on the database; document models can be flexible
Querying SQL Database-specific query APIs or languages
Examples MySQL, PostgreSQL, SQL Server MongoDB, Redis, Cassandra
Common use cases Transactions, financial records, related data Document-oriented data, caching, distributed data workloads
Neither SQL nor NoSQL is automatically better for every application. Choose based on data structure, consistency requirements, queries, scalability needs, and the capabilities of the database.

5. How Does Node.js Communicate with a Database?

Node.js applications generally use a database driver or an appropriate library to communicate with a database. The application sends queries or operations through that library and receives results.

Client

Browser or API consumer sends a request

↓
Node.js Application

Processes the request and applies business logic

↓
Database Driver or Library

Sends database operations to the database server

↓
Database

Stores data or executes the requested operation

↓
API Response

Node.js sends the result back to the client

6. Connecting Node.js to Different Databases

Node.js supports multiple databases through their drivers and libraries. The package and connection code depend on the database being used.

Database Common Node.js Package Data Model
MySQL mysql2 Relational tables
MongoDB mongodb or mongoose Documents
PostgreSQL pg Relational tables
Microsoft SQL Server mssql Relational tables

For example, the mysql2 package allows Node.js to connect to MySQL, while the MongoDB driver allows Node.js to work with MongoDB collections and documents.

7. Example: Data in Memory vs Database

JavaScript arrays can temporarily hold data while a Node.js process is running. However, they are not a replacement for persistent database storage in most applications.

JavaScript
// Data stored only in application memory
let products = [
    { id: 1, name: 'Laptop', price: 50000 },
    { id: 2, name: 'Mobile', price: 20000 }
];

console.log(products);

This array is easy to use for demonstrations, but its contents are not automatically saved to a database.

In a real application, Node.js can retrieve the product records from MySQL or MongoDB and return them through an API.

Remember: Using an array is useful for learning JavaScript and API basics. Use an appropriate persistent storage solution when application data must survive a restart.

8. Common Database Operations

Applications commonly perform four basic operations on stored data. These are known as CRUD operations.

Operation Purpose Example
Create Add a new record Add a new product
Read Retrieve existing records Display all products
Update Modify existing records Change a product's price
Delete Remove records Delete a discontinued product

In the upcoming lessons, we will explore database integration, querying, CRUD operations, and connection management in more detail.

Important Points to Remember

  • A database stores and organizes application data.
  • Node.js can communicate with databases through drivers and libraries.
  • MySQL and SQL Server are relational databases.
  • MongoDB is a document-oriented NoSQL database.
  • Database selection depends on application requirements.
  • CRUD stands for Create, Read, Update, and Delete.
  • In-memory JavaScript data is not automatically persistent.
  • Database credentials should be protected.

Summary

Databases store application data in an organized and persistent manner. Node.js applications communicate with databases through appropriate drivers or libraries to perform operations such as inserting, retrieving, updating, and deleting records.

In the next lesson, we will learn how to integrate MySQL with Node.js using the mysql2 package.