Published on

MongoDB with Node.js and TypeScript: Practical CRUD Examples for Modern Applications

Authors
  • avatar
    Name
    Jonas de Oliveira
    Twitter

In today’s fast-paced development world, flexibility and scalability are key for modern applications. MongoDB, a NoSQL document database, provides an innovative approach to storing data with a flexible schema. In this article, we'll demonstrate practical examples of how to integrate MongoDB with Node.js using TypeScript by implementing CRUD (Create, Read, Update, Delete) operations. These examples will help you see how MongoDB can be used in real-world applications, reinforcing your technical expertise and catching the attention of recruiters.

What is MongoDB?

MongoDB is a NoSQL database that stores data in flexible documents (using BSON, a binary form of JSON). Unlike relational databases, MongoDB doesn’t enforce a fixed schema, allowing you to store data in a dynamic and adaptable format. This flexibility is ideal for agile projects where data structures evolve over time.

Why Use MongoDB with Node.js and TypeScript?

  • Flexibility: MongoDB’s document-based storage allows dynamic data structures.
  • Scalability: Easily scale horizontally with sharding.
  • Performance: High read/write performance suited for high-traffic applications.
  • Type Safety: Using TypeScript helps catch errors at compile time and improves code maintainability.
  • Modern Development: Integrates smoothly with modern Node.js applications, making it a popular choice for web and mobile apps.

Setting Up the Environment

Install MongoDB

You can install MongoDB locally or use a managed cloud service like MongoDB Atlas.

Create a Node.js Project

Create a new folder for your project and initialize a Node.js project:

mkdir mongodb-node-ts
cd mongodb-node-ts
npm init -y

Install Dependencies

Install the official MongoDB driver along with TypeScript and its related packages:

npm install mongodb
npm install --save-dev typescript ts-node @types/node

Create a TypeScript Configuration File

Create a tsconfig.json file in the root of your project:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "outDir": "./dist"
  },
  "include": ["src"]
}

Practical Example: CRUD Operations in Node.js with TypeScript

Below is a practical example demonstrating how to connect to MongoDB and perform CRUD operations using Node.js and TypeScript. Create a folder named src and inside it, create a file called index.ts with the following content:

// src/index.ts

import { MongoClient, ObjectId } from 'mongodb';

// Define the interface for our Product document
interface Product {
  _id?: ObjectId; // Optional because it will be added by MongoDB
  name: string;
  price: number;
  category: string;
}

// MongoDB connection URL and database name
const url = 'mongodb://localhost:27017';
const dbName = 'exampleDB';

// Main function to perform CRUD operations
async function main() {
  // Create a new MongoClient instance
  const client = new MongoClient(url);

  try {
    // Connect to the MongoDB server
    await client.connect();
    console.log('Connected to MongoDB');

    // Select the database
    const db = client.db(dbName);

    // Select (or create) the collection 'products'
    const collection = db.collection<Product>('products');

    // --- Create: Insert a new product ---
    const newProduct: Product = {
      name: 'Sample Product',
      price: 100,
      category: 'E-commerce',
    };

    // Insert the product into the collection
    const insertResult = await collection.insertOne(newProduct);
    console.log(`Inserted product with _id: ${insertResult.insertedId}`);

    // --- Read: Find all products ---
    const products = await collection.find({}).toArray();
    console.log('Products found:', products);

    // --- Update: Update the price of the inserted product ---
    const filter = { _id: insertResult.insertedId };
    const updateDoc = { $set: { price: 150 } };
    const updateResult = await collection.updateOne(filter, updateDoc);
    console.log(`Updated documents: ${updateResult.modifiedCount}`);

    // --- Delete: Remove the updated product ---
    const deleteResult = await collection.deleteOne(filter);
    console.log(`Deleted documents: ${deleteResult.deletedCount}`);
  } catch (error) {
    console.error('Error performing operations:', error);
  } finally {
    // Close the connection to MongoDB
    await client.close();
    console.log('Disconnected from MongoDB');
  }
}

// Execute the main function
main().catch(console.error);

Code Comments Explained

  • Connection Setup:
    • We import MongoClient and ObjectId from the MongoDB driver.
    • The connection URL and database name are defined for local development.
  • Interface Definition:
    • The Product interface defines the structure of a product document.
  • CRUD Operations:
    • Create: Inserts a new product document into the products collection.
    • Read: Retrieves all documents from the collection.
    • Update: Updates the price of the newly inserted product.
    • Delete: Removes the product document from the collection.
  • Error Handling and Cleanup:
    • The try...catch...finally block ensures that errors are handled gracefully and that the MongoDB connection is closed regardless of success or failure.

Running the Code

To run the example, execute the following command in your project root:

npx ts-node src/index.ts

You should see console messages confirming the connection to MongoDB and the results of each CRUD operation.

Final Thoughts

Integrating MongoDB with Node.js using TypeScript is a practical and efficient way to build modern applications. By leveraging TypeScript’s static typing and MongoDB’s flexible document model, you can create robust, scalable, and maintainable systems. This practical example demonstrates the essential CRUD operations, showcasing your ability to implement real-world solutions.