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

MongoDB Integration in Node.js

Learn how to connect a Node.js application to MongoDB, create collections, insert documents, and retrieve data using the MongoDB Node.js driver.

MongoDB is a NoSQL document database. It stores data as documents in BSON format, which is similar to JSON. Documents are grouped into collections instead of traditional relational tables.

For example, an online shopping application can store product information in a MongoDB collection and retrieve it whenever a client requests product details.

Remember: Node.js handles application logic, MongoDB stores documents, and the MongoDB Node.js driver allows the application to communicate with the database.

1. What Is MongoDB?

MongoDB is a document-oriented NoSQL database. Instead of storing information in rows and columns, it stores documents containing fields and values.

For example, a product document may look like this:

JSON
{
    "_id": 1,
    "name": "Laptop",
    "price": 50000,
    "category": "Electronics"
}

Multiple product documents can be stored in a collection named products.

MongoDB Concept Meaning
Database Contains collections.
Collection Groups related documents.
Document Stores a record as fields and values.
Field Represents an individual property, such as name or price.
_id Identifies a document uniquely within its collection.

2. SQL Tables vs MongoDB Collections

Relational databases organize records into tables. MongoDB organizes related documents into collections.

Relational Database MongoDB
Database Database
Table Collection
Row Document
Column Field
SQL query MongoDB query using the driver or query language
MongoDB documents can have different fields within the same collection, although applications can enforce a consistent schema when needed.

3. Installing the MongoDB Driver

To connect Node.js to MongoDB, install the official MongoDB Node.js driver. Express can also be installed if you want to expose database operations through REST API endpoints.

Terminal
npm init -y
npm install express mongodb

A basic project structure looks like this:

Text
mongodb-node-app/
│
├── node_modules/
├── package.json
├── package-lock.json
└── app.js
Installing the MongoDB driver does not install the database server. You must have a MongoDB server running locally or have access to a MongoDB deployment such as MongoDB Atlas.

4. Connecting Node.js to MongoDB

The MongoDB driver provides the MongoClient class for connecting to a MongoDB deployment. Once connected, the application can access a database and its collections.

JavaScript
const { MongoClient } = require('mongodb');

const uri = process.env.MONGODB_URI;

const client = new MongoClient(uri);

async function connectDatabase() {
    try {
        await client.connect();

        console.log('Connected to MongoDB successfully!');

        const database = client.db('nodejsdb');

        console.log('Database selected:', database.databaseName);
    } catch (error) {
        console.error('MongoDB connection failed:', error.message);
    }
}

connectDatabase();

Understanding the important parts:

Code Purpose
MongoClient Creates a client for communicating with MongoDB.
process.env.MONGODB_URI Reads the connection URI from an environment variable.
client.connect() Establishes the database connection.
client.db('nodejsdb') Selects the database named nodejsdb.
try...catch Handles connection errors.
Set the MONGODB_URI environment variable to your actual connection string before running this example. Do not expose database credentials in source code or public repositories.

5. Inserting a Document

MongoDB provides the insertOne() method to insert a single document into a collection.

JavaScript
const { MongoClient } = require('mongodb');

async function insertProduct() {
    const client = new MongoClient(process.env.MONGODB_URI);

    try {
        await client.connect();

        const database = client.db('nodejsdb');
        const products = database.collection('products');

        const result = await products.insertOne({
            name: 'Laptop',
            price: 50000,
            category: 'Electronics'
        });

        console.log('Inserted document ID:', result.insertedId);
    } catch (error) {
        console.error('Insert failed:', error.message);
    } finally {
        await client.close();
    }
}

insertProduct();

If the insert succeeds, MongoDB creates an _id for the document when one is not supplied. The insertedId property contains the ID of the newly inserted document.

6. Retrieving Documents

Use find() to retrieve multiple documents and findOne() to retrieve a single matching document.

JavaScript
const { MongoClient } = require('mongodb');

async function getProducts() {
    const client = new MongoClient(process.env.MONGODB_URI);

    try {
        await client.connect();

        const database = client.db('nodejsdb');
        const products = database.collection('products');

        const allProducts = await products.find({}).toArray();

        console.log(allProducts);
    } catch (error) {
        console.error('Read failed:', error.message);
    } finally {
        await client.close();
    }
}

getProducts();

The empty filter {} matches all documents in the collection. The toArray() method collects the matching documents into a JavaScript array.

Example output:

JSON
[
    {
        "_id": "generated MongoDB ObjectId",
        "name": "Laptop",
        "price": 50000,
        "category": "Electronics"
    }
]

7. Updating a Document

Use updateOne() to update fields in the first document that matches a filter. The $set operator changes the specified fields without replacing the entire document.

JavaScript
const result = await products.updateOne(
    { name: 'Laptop' },
    {
        $set: {
            price: 55000
        }
    }
);

console.log('Matched documents:', result.matchedCount);
console.log('Modified documents:', result.modifiedCount);

In this example, the price of the first matching Laptop document is updated to 55000. The matchedCount and modifiedCount properties help identify the result of the operation.

8. Deleting a Document

Use deleteOne() to delete the first document matching a filter. Always make sure the filter identifies the intended document.

JavaScript
const result = await products.deleteOne({
    name: 'Laptop'
});

console.log('Deleted documents:', result.deletedCount);

If a matching document is found and deleted, deletedCount will usually be 1. If no document matches, it will be 0.

Be careful with delete operations. A filter that does not identify the intended document may delete the wrong record.

9. Complete Example: Express with MongoDB

The following example creates a simple REST API that retrieves products from MongoDB. It uses one MongoClient connection for the application and closes it when the server shuts down.

JavaScript
const express = require('express');
const { MongoClient } = require('mongodb');

const app = express();

app.use(express.json());

const client = new MongoClient(process.env.MONGODB_URI);

let products;

app.get('/api/products', async (req, res) => {
    try {
        const result = await products.find({}).toArray();

        res.status(200).json(result);
    } catch (error) {
        console.error('Database query failed:', error.message);

        res.status(500).json({
            message: 'Unable to retrieve products'
        });
    }
});

async function startServer() {
    try {
        await client.connect();

        const database = client.db('nodejsdb');
        products = database.collection('products');

        app.listen(3000, () => {
            console.log('Server running at http://localhost:3000');
        });
    } catch (error) {
        console.error('MongoDB connection failed:', error.message);
        await client.close();
        process.exit(1);
    }
}

startServer();

async function shutdown() {
    await client.close();
    process.exit(0);
}

process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);

Start the application:

Terminal
node app.js

Send this GET request using Postman or a browser:

HTTP
GET http://localhost:3000/api/products

If the connection succeeds, the endpoint returns the documents stored in the products collection.

This example assumes MONGODB_URI is configured and the MongoDB deployment is reachable. For a production application, also add request validation, authentication, authorization, and suitable database indexes.

10. MongoDB Integration Flow

Client

Sends an HTTP request

↓
Express Route

Processes the request

↓
MongoDB Node.js Driver

Executes the database operation

↓
MongoDB Collection

Stores or retrieves documents

↓
JSON Response

Returns the result to the client

Important Points to Remember

  • MongoDB is a document-oriented NoSQL database.
  • Documents are grouped into collections.
  • Install the mongodb package to use the official driver.
  • Use MongoClient to connect to MongoDB.
  • Use insertOne() to insert a document.
  • Use find() and findOne() to retrieve documents.
  • Use updateOne() to update a matching document.
  • Use deleteOne() to delete a matching document.
  • Protect connection strings and database credentials.
  • Handle database errors and close resources properly.

Summary

MongoDB stores data as documents grouped into collections. Node.js applications can connect to MongoDB using the official MongoDB driver and perform insert, read, update, and delete operations. Express routes can expose these operations through REST API endpoints.

In the next lesson, we will learn how to perform CRUD operations in a Node.js database application.