NPM Install MongoDB: How to Install MongoDB Using Node.js

Photo of Jim Kutz
Jim Kutz
December 19, 2025

Summarize this article with:

✨ AI Generated Summary

Setting up MongoDB with Node.js shouldn't require hours of troubleshooting connection errors. Yet many developers spend more time debugging driver configurations than writing application logic.

This guide walks you through installing the MongoDB Node.js driver via npm and establishing your first database connection fast.

TL;DR

  • Install the official MongoDB driver with npm to connect Node.js apps directly to MongoDB without extra abstractions.

  • Set up a reusable database connection using MongoClient and connection pooling instead of reconnecting per request.

  • Configure connection options early like pool size and timeouts to avoid hangs and resource exhaustion in production.

  • Choose the native driver or Mongoose based on structure needs, not habit. Use the driver for flexibility and performance, Mongoose for enforced schemas and modeling.

What Do You Need Before Installing MongoDB with npm?

Before running npm install, confirm you have these components ready:

  • Node.js (v14 or higher): Check your version with node --version
  • npm (v6 or higher): Bundled with Node.js, verify with npm --version
  • MongoDB instance: Either a local installation or MongoDB Atlas cloud cluster
  • A Node.js project: Initialized with npm init

How Do You Install the MongoDB Driver with npm?

The official MongoDB Node.js driver is the recommended package for connecting your application to MongoDB. Run this command in your project directory:

npm install mongodb

This installs the latest stable version. For production applications where you need version consistency, specify an exact version:

npm install mongodb@6.3.0

Verifying Your Installation

Check that the driver was added correctly by examining your package.json:

"dependencies": {
  "mongodb": "^6.3.0"
}

How Do You Connect to MongoDB from Node.js?

Create a new file called db.js and add the following connection code:

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


// Replace with your connection string
const uri = 'mongodb://localhost:27017';


async function connectToDatabase() {
  const client = new MongoClient(uri);
  
  try {
    await client.connect();
    console.log('Connected to MongoDB');
    return client;
  } catch (error) {
    console.error('Connection failed:', error);
    throw error;
  }
}

Connecting to MongoDB Atlas

For cloud-hosted MongoDB Atlas clusters, your connection string includes authentication credentials:

const uri = 'mongodb+srv://<username>:<password>@cluster.mongodb.net/<database>';

Replace the placeholders with your Atlas credentials. Never hardcode credentials in production code. Use environment variables instead.

How Do You Perform Basic CRUD Operations?

Once connected, you can interact with your database using these core operations:

Operation Purpose Example
Insert one document Add a new record to the collection await collection.insertOne({ name: "John" });
Find one document Retrieve a single matching record await collection.findOne({ name: "John" });
Update one document Modify fields on an existing record await collection.updateOne({ name: "John" }, { $set: { age: 30 } });
Delete one document Remove a matching record await collection.deleteOne({ name: "John" });

What Connection Options Should You Configure?

Production applications benefit from explicit connection settings:

const client = new MongoClient(uri, {

  maxPoolSize: 10,

  serverSelectionTimeoutMS: 5000,

  socketTimeoutMS: 45000,

});

Option What it controls Why it matters
maxPoolSize Maximum number of connections in the pool Prevents connection exhaustion and helps control resource usage under load
serverSelectionTimeoutMS How long the driver waits to find an available server Fails fast when the cluster is unreachable instead of hanging requests
socketTimeoutMS How long the driver waits for a socket operation to complete Avoids stalled reads or writes when the network or server is slow

How Do You Troubleshoot Common Installation Errors?

These errors appear frequently when setting up MongoDB with Node.js:

MongoNetworkError: connect ECONNREFUSED

This indicates MongoDB isn't running or isn't accessible at the specified address. Verify your MongoDB service is running and the connection string points to the correct host and port.

Authentication Failed

Double-check your username, password, and authentication database. For Atlas connections, ensure your IP address is whitelisted in the Network Access settings.

Cannot Find Module 'mongodb'

Run npm install mongodb in your project root. Confirm the package appears in your package.json dependencies.

Should You Use MongoDB Driver or Mongoose?

The native MongoDB driver gives you direct database access with full control. Mongoose adds a schema layer and object modeling on top of the driver.

Aspect MongoDB Driver Mongoose
Schema validation Optional, handled at the database level Built-in and enforced through schemas
Performance Lower overhead with direct database access Slight overhead due to ODM abstraction
Learning curve Closer to raw MongoDB concepts More abstracted, Rails-like developer experience
Best suited for Flexible schemas and low-level control Structured applications that need validation and modeling

For applications requiring strict data validation and relationships, consider Mongoose. For data pipelines and ETL workflows where schema flexibility matters, the native driver provides more direct control.

How Do You Move MongoDB Data to Your Data Warehouse?

Once your application writes to MongoDB, you'll likely need that data in your analytics stack. Manual extraction scripts work initially but become maintenance burdens as data volumes grow and schemas evolve.

Airbyte's MongoDB connector handles CDC replication to Snowflake, BigQuery, or Databricks with schema propagation that tracks your document structure changes automatically. This removes the custom ETL code that data engineers typically maintain when MongoDB serves as an application database feeding downstream analytics.

Ready to replicate MongoDB data without writing extraction scripts? Try Airbyte and connect MongoDB to your data warehouse in minutes.

Frequently Asked Questions

What version of Node.js is required for the MongoDB driver?

The latest MongoDB Node.js driver (v6.x) requires Node.js 14 or higher. For older Node.js versions, install mongodb@4.x which supports Node.js 12+.

Can I use ES modules instead of CommonJS?

Yes. Replace require statements with import syntax. Add "type": "module" to your package.json or use the .mjs file extension.

Should I close the MongoDB connection after each operation?

No. Connection pooling handles this efficiently. Create one client instance at application startup and reuse it throughout your application's lifecycle. Close the connection only when shutting down.

How do I handle connection failures gracefully?

Wrap connection logic in try-catch blocks and implement retry logic with exponential backoff. The driver's serverSelectionTimeoutMS option controls how long to wait before timing out.

Limitless data movement with free Alpha and Beta connectors
Introducing: our Free Connector Program
The data movement infrastructure for the modern data teams.
Try a 30-day free trial
Photo of Jim Kutz