Node.js Connect to MongoDB

Node.js Connect to MongoDB – In this Node.js Tutorial, we shall learn to connect to MongoDB from Node.js Application.

A Node.js application connects to MongoDB through a MongoDB connection string and the MongoDB Node.js driver. Once connected, the application can select a database, open a collection, and perform operations such as insert, find, update, and delete.

The prerequisite to connect to a MongoDB, is having MongoDB installed in the computer. If you have not installed MongoDB yet, refer this tutorial – Install MongoDB.

Node.js MongoDB connection requirements

  • Node.js and npm installed on your system.
  • A running MongoDB server, either local MongoDB or a hosted MongoDB cluster.
  • The mongodb npm package installed in your Node.js project.
  • A MongoDB URI such as mongodb://127.0.0.1:27017 for local MongoDB, or an authenticated URI for a remote cluster.

Steps to Connect to MongoDB via Node.js

To connect to MongoDB from Node.js Application, following is a step by step guide.

Step 1: Start MongoDB service.

Run the following command to start MongoDB Service.

sudo service mongod start

On some systems, especially newer Linux distributions, MongoDB may be managed through systemctl.

</>
Copy
sudo systemctl start mongod
sudo systemctl status mongod

Step 2: Install mongodb package using npm (if not installed already).

arjun@nodejs:~/workspace/nodejs/mongodb$ npm install mongodb
npm WARN saveError ENOENT: no such file or directory, open '/home/arjun/workspace/nodejs/package.json'
npm WARN enoent ENOENT: no such file or directory, open '/home/arjun/workspace/nodejs/package.json'
npm WARN nodejs No description
npm WARN nodejs No repository field.
npm WARN nodejs No README data
npm WARN nodejs No license field.

+ mongodb@2.2.33
added 9 packages in 9.416s

The installation output above is from the original example. For a new project, create a project folder with package.json first and then install the MongoDB driver.

</>
Copy
mkdir node-mongodb-connection
cd node-mongodb-connection
npm init -y
npm install mongodb

Step 3: Prepare the url.

A simple hack to know the base url of MongoDB Service is to Open a Terminal and run Mongo Shell.

arjun@nodejs:~$ mongo
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.9
Server has startup warnings: 
2017-10-29T18:15:36.110+0530 I STORAGE  [initandlisten] 

While the Mongo Shell starts up, it echoes back the base url of MongoDB.

mongodb://127.0.0.1:27017

In many current MongoDB installations, mongosh is used instead of the older mongo shell. The local connection string is still usually based on host 127.0.0.1 and port 27017.

</>
Copy
mongosh "mongodb://127.0.0.1:27017"

Step 4: With the help of mongodb package, create a MongoClient and connect to the url.

Example 1 – Connect to MongoDB via Node.js

Following is an Example Node.js program to make a Node.js MongoDB Connection.

node-js-mongodb-connection.js

</>
Copy
// URL at which MongoDB service is running
var url = "mongodb://localhost:27017";

// A Client to MongoDB
var MongoClient = require('mongodb').MongoClient;

// Make a connection to MongoDB Service
MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log("Connected to MongoDB!");
  db.close();
});

Output

arjun@java:~/workspace/nodejs/mongodb$ node node-js-mongodb-connection.js 
Connected to MongoDB!

The callback-based example above is useful for understanding the basic idea of MongoClient.connect(). In new Node.js applications, you will often see the same connection written with async and await.

Modern Node.js MongoDB connection example with async and await

The following example connects to a local MongoDB server, selects a database named school, checks one collection, and then closes the client in a finally block.

connect-modern.js

</>
Copy
const { MongoClient } = require('mongodb');

const uri = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(uri);

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

    const database = client.db('school');
    const students = database.collection('students');

    const count = await students.countDocuments();
    console.log(`Connected to MongoDB. Student count: ${count}`);
  } catch (error) {
    console.error('MongoDB connection failed:', error);
  } finally {
    await client.close();
  }
}

connectToMongoDB();

Run the file with Node.js.

</>
Copy
node connect-modern.js

If the database and collection are empty, the connection can still succeed. MongoDB creates databases and collections when data is written, so an empty development database may not show much output until you insert documents.

MongoDB connection string for local Node.js development

For local development, the connection string usually follows this format.

</>
Copy
mongodb://host:port

For example, a local MongoDB server running on the default port can be accessed with either of the following connection strings.

</>
Copy
mongodb://127.0.0.1:27017
mongodb://localhost:27017

If localhost does not work on your system, try 127.0.0.1. This can avoid name resolution or IPv6-related issues on some development machines.

Connect Node.js to MongoDB using an environment variable

For applications that connect to a hosted MongoDB database, do not place real usernames and passwords directly in the JavaScript file. Keep the connection string in an environment variable and read it from process.env.

</>
Copy
export MONGODB_URI="mongodb://127.0.0.1:27017"
</>
Copy
const { MongoClient } = require('mongodb');

const uri = process.env.MONGODB_URI;

if (!uri) {
  throw new Error('MONGODB_URI environment variable is not set');
}

const client = new MongoClient(uri);

For a production application, also check authentication, network access, TLS settings, and database user permissions based on where your MongoDB server is hosted.

Reuse a MongoDB client in a Node.js server application

For a one-time script, it is fine to connect, run the task, and close the client. For a web server, avoid opening a new MongoDB connection for every request. Create the client once and reuse it while the application is running.

</>
Copy
const { MongoClient } = require('mongodb');

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

async function getDatabase() {
  if (!database) {
    await client.connect();
    database = client.db('school');
  }

  return database;
}

module.exports = { getDatabase };

This pattern helps keep connection handling in one place. In a larger application, you can import getDatabase() wherever database access is needed.

Check the Node.js MongoDB connection with a ping command

A simple way to verify the connection is to run the MongoDB ping command from Node.js. This confirms that the client can reach the server and execute a database command.

</>
Copy
const { MongoClient } = require('mongodb');

const uri = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(uri);

async function pingMongoDB() {
  try {
    await client.connect();
    await client.db('admin').command({ ping: 1 });
    console.log('MongoDB ping successful');
  } catch (error) {
    console.error('MongoDB ping failed:', error.message);
  } finally {
    await client.close();
  }
}

pingMongoDB();

Node.js MongoDB connection troubleshooting

If your Node.js application cannot connect to MongoDB, check these common causes.

  • MongoDB service is not running: Start the local MongoDB service and confirm that it is listening on the expected port.
  • Wrong connection string: Check the host, port, username, password, database name, and connection options.
  • Authentication failure: Verify that the database user exists and has the required permissions.
  • Network access blocked: For a remote database, check firewall rules, IP allow lists, and cluster network settings.
  • Client closes too early: Make sure asynchronous MongoDB operations are awaited before calling client.close().

Node.js MongoDB connection methods and files checklist

  • Confirm that the example imports MongoClient from the mongodb package.
  • Use mongodb://127.0.0.1:27017 or the correct hosted connection string for the test environment.
  • Keep real MongoDB credentials out of the tutorial code and screenshots.
  • Check that every async MongoDB call is awaited before the client is closed.
  • Test the code with a safe development database before publishing the article.

Node.js Connect to MongoDB FAQs

How do I connect Node.js to MongoDB?

Install the mongodb package, import MongoClient, create a client with a MongoDB URI, call connect(), select a database with db(), and close the client when the script is finished.

What is the local MongoDB URL for Node.js?

The usual local MongoDB URL is mongodb://127.0.0.1:27017. You may also see mongodb://localhost:27017, but 127.0.0.1 can be more predictable on some systems.

Should a Node.js app create a new MongoDB connection for every request?

No. For a server application, create the MongoDB client once and reuse it across requests. Opening and closing a connection for every request adds unnecessary overhead and can cause connection management problems.

Can Node.js connect to MongoDB Atlas?

Yes. Use the MongoDB Atlas connection string instead of the local URI. Store the connection string in an environment variable, and confirm that the database user, password, and network access settings are correct.

Why does MongoClient connect fail in Node.js?

Common reasons include a stopped MongoDB service, incorrect URI, blocked network access, invalid credentials, missing IP allow list entry for a hosted database, or closing the client before asynchronous operations finish.

Reference documentation for connecting Node.js and MongoDB

For current driver options and connection examples, refer to the official MongoDB Node.js driver documentation. For the next tutorial in this series, continue with Node.js MongoDB.

Conclusion: Node.js MongoDB connection example

In this Node.js MongoDB – Node.js Connect to MongoDB, we have learnt to find the url of the MongoDB Service and connect to the service from Node.js using MongoClient’s connect method, demonstrated by an Example program.

We also covered the modern async/await style, environment-variable based connection strings, reusable MongoDB clients for server applications, and common connection errors to check during development.