codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🟢

Node.js

31 / 63 topics
30Database Integration31MongoDB with Node.js32Mongoose ORM33SQL Databases with Node.js34Sequelize ORM
Tutorials/Node.js/MongoDB with Node.js
🟢Node.js

MongoDB with Node.js

Updated 2026-04-20
3 min read

Introduction

MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents. It's highly scalable and can handle large volumes of data efficiently. In this tutorial, we'll explore how to integrate MongoDB with Node.js using the mongodb package. This guide will cover setting up your environment, connecting to a MongoDB database, performing CRUD operations, and implementing best practices.

Prerequisites

Before you begin, ensure you have the following installed:

  • Node.js: Version 14 or higher.
  • MongoDB: You can use either a local instance or a cloud-based service like MongoDB Atlas.
  • npm (comes with Node.js).

Setting Up Your Project

First, create a new directory for your project and initialize it using npm.

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

Next, install the mongodb package:

npm install mongodb

Connecting to MongoDB

To connect to a MongoDB database, you'll need to use the MongoClient class from the mongodb package. Here's how you can set up a connection:

  1. Create a Connection File: Create a file named db.js.
// db.js
const { MongoClient } = require('mongodb');

async function connectToDatabase() {
  const uri = 'your_mongodb_connection_string'; // Replace with your MongoDB URI
  const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

  try {
    await client.connect();
    console.log('Connected to MongoDB');
    return client.db('your_database_name'); // Replace with your database name
  } catch (error) {
    console.error('Error connecting to MongoDB', error);
    throw error;
  }
}

module.exports = connectToDatabase;
  1. Environment Variables: For security reasons, it's best practice to store your connection string in an environment variable.
# .env file
MONGODB_URI=your_mongodb_connection_string
DATABASE_NAME=your_database_name

Update db.js to use the environment variables:

// db.js
require('dotenv').config();
const { MongoClient } = require('mongodb');

async function connectToDatabase() {
  const uri = process.env.MONGODB_URI;
  const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

  try {
    await client.connect();
    console.log('Connected to MongoDB');
    return client.db(process.env.DATABASE_NAME);
  } catch (error) {
    console.error('Error connecting to MongoDB', error);
    throw error;
  }
}

module.exports = connectToDatabase;

Performing CRUD Operations

Now that you have a connection, let's perform some basic CRUD operations.

Creating Documents

  1. Create a File for CRUD Operations: Create a file named operations.js.
// operations.js
const { ObjectId } = require('mongodb');
const connectToDatabase = require('./db');

async function createDocument(collectionName, document) {
  const db = await connectToDatabase();
  const collection = db.collection(collectionName);
  try {
    const result = await collection.insertOne(document);
    console.log('Document inserted:', result.insertedId);
    return result.insertedId;
  } catch (error) {
    console.error('Error inserting document', error);
    throw error;
  }
}

module.exports = { createDocument };
  1. Using the Create Function: You can now use this function to insert documents into your collection.
// index.js
const { createDocument } = require('./operations');

async function run() {
  const document = { name: 'John Doe', age: 30, email: 'john.doe@example.com' };
  await createDocument('users', document);
}

run().catch(console.error);

Reading Documents

  1. Add a Read Function: Update operations.js to include a read function.
// operations.js
async function readDocuments(collectionName, query = {}) {
  const db = await connectToDatabase();
  const collection = db.collection(collectionName);
  try {
    const documents = await collection.find(query).toArray();
    console.log('Documents found:', documents);
    return documents;
  } catch (error) {
    console.error('Error reading documents', error);
    throw error;
  }
}

module.exports = { createDocument, readDocuments };
  1. Using the Read Function: Use this function to fetch documents from your collection.
// index.js
const { createDocument, readDocuments } = require('./operations');

async function run() {
  const document = { name: 'Jane Doe', age: 25, email: 'jane.doe@example.com' };
  await createDocument('users', document);

  const users = await readDocuments('users');
}

run().catch(console.error);

Updating Documents

  1. Add an Update Function: Update operations.js to include an update function.
// operations.js
async function updateDocument(collectionName, filter, update) {
  const db = await connectToDatabase();
  const collection = db.collection(collectionName);
  try {
    const result = await collection.updateOne(filter, { $set: update });
    console.log('Documents updated:', result.modifiedCount);
    return result.modifiedCount;
  } catch (error) {
    console.error('Error updating document', error);
    throw error;
  }
}

module.exports = { createDocument, readDocuments, updateDocument };
  1. Using the Update Function: Use this function to update documents in your collection.
// index.js
const { createDocument, readDocuments, updateDocument } = require('./operations');

async function run() {
  const document = { name: 'John Doe', age: 30, email: 'john.doe@example.com' };
  await createDocument('users', document);

  const filter = { name: 'John Doe' };
  const update = { age: 31 };

  await updateDocument('users', filter, update);
}

run().catch(console.error);

Deleting Documents

  1. Add a Delete Function: Update operations.js to include a delete function.
// operations.js
async function deleteDocument(collectionName, filter) {
  const db = await connectToDatabase();
  const collection = db.collection(collectionName);
  try {
    const result = await collection.deleteOne(filter);
    console.log('Documents deleted:', result.deletedCount);
    return result.deletedCount;
  } catch (error) {
    console.error('Error deleting document', error);
    throw error;
  }
}

module.exports = { createDocument, readDocuments, updateDocument, deleteDocument };
  1. Using the Delete Function: Use this function to delete documents from your collection.
// index.js
const { createDocument, readDocuments, updateDocument, deleteDocument } = require('./operations');

async function run() {
  const document = { name: 'John Doe', age: 30, email: 'john.doe@example.com' };
  await createDocument('users', document);

  const filter = { name: 'John Doe' };

  await deleteDocument('users', filter);
}

run().catch(console.error);

Best Practices

  • Error Handling: Always handle errors gracefully. Use try-catch blocks and log errors appropriately.

  • Connection Management: Ensure that your MongoDB connection is properly managed. Consider using a connection pool or a connection management library like mongoose.

  • Environment Variables: Store sensitive information like database URIs in environment variables.

  • Asynchronous Operations: Use async/await to handle asynchronous operations, making your code cleaner and easier to read.

  • Validation: Validate user input before inserting it into the database to prevent errors and ensure data integrity.

Conclusion

In this tutorial, we've covered how to integrate MongoDB with Node.js using the mongodb package. We explored setting up a connection, performing CRUD operations, and implementing best practices. By following these steps, you should be able to build robust applications that interact with MongoDB effectively.


PreviousDatabase IntegrationNext Mongoose ORM

Recommended Gear

Database IntegrationMongoose ORM