Connecting MongoDB with NodeJS

To connect MongoDB with Node.js, use the MongoClient.connect() method from the mongodb package. This asynchronous method establishes a connection between your Node.js application and the MongoDB server.

Syntax

MongoClient.connect(url, options, callback)

Parameters:

  • url − Connection string specifying the MongoDB server location and port
  • options − Optional configuration object (e.g., useUnifiedTopology: true)
  • callback − Function executed after connection attempt with error and client parameters

Installation and Setup

First, install the MongoDB driver for Node.js ?

npm install mongodb --save

Start your MongoDB server ?

mongod --dbpath=data --bind_ip 127.0.0.1

Example

Create a file MongodbConnect.js with the following code ?

// Import the MongoDB client
const MongoClient = require("mongodb").MongoClient;

// MongoDB connection URL
const url = 'mongodb://localhost:27017/';

// Database name
const dbname = "Employee";

// Connect to MongoDB
MongoClient.connect(url, { useUnifiedTopology: true }, (err, client) => {
    if (!err) {
        console.log("Successfully connected to MongoDB server");
        
        // Access the database
        const db = client.db(dbname);
        console.log(`Connected to database: ${dbname}`);
        
        // Close the connection
        client.close();
    } else {
        console.log("Error connecting to MongoDB:", err.message);
    }
});

Run the application ?

node MongodbConnect.js

Output

C:\Users\tutorialsPoint\> node MongodbConnect.js
Successfully connected to MongoDB server
Connected to database: Employee

Key Points

  • Always include { useUnifiedTopology: true } in options to avoid deprecation warnings
  • Use client.db(dbname) to access a specific database after connection
  • Remember to call client.close() to properly close the connection
  • Handle connection errors appropriately in the callback function

Conclusion

MongoClient.connect() provides a straightforward way to establish connections between Node.js and MongoDB. Always include proper error handling and connection management for production applications.

Updated on: 2026-03-15T03:57:40+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements