0
0
NodejsHow-ToBeginner · 3 min read

How to Connect to MongoDB in Node.js: Simple Guide

To connect to MongoDB in Node.js, use the official mongodb package and create a MongoClient with your connection string. Then call connect() on the client to establish the connection before performing database operations.
📐

Syntax

Here is the basic syntax to connect to MongoDB using the official mongodb Node.js driver:

  • Import the MongoClient class from the mongodb package.
  • Create a new MongoClient instance with your MongoDB connection URI.
  • Call the asynchronous connect() method on the client to open the connection.
  • Use the client to access databases and collections.
  • Close the connection when done.
javascript
import { MongoClient } from 'mongodb';

const uri = 'your-mongodb-connection-string';
const client = new MongoClient(uri);

async function run() {
  try {
    await client.connect();
    // Use client.db() to access database
  } finally {
    await client.close();
  }
}

run().catch(console.dir);
💻

Example

This example shows how to connect to a MongoDB database, list the database names, and then close the connection.

javascript
import { MongoClient } from 'mongodb';

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

async function run() {
  try {
    await client.connect();
    console.log('Connected successfully to MongoDB');

    const databasesList = await client.db().admin().listDatabases();
    console.log('Databases:');
    databasesList.databases.forEach(db => console.log(` - ${db.name}`));
  } catch (err) {
    console.error('Connection error:', err);
  } finally {
    await client.close();
    console.log('Connection closed');
  }
}

run();
Output
Connected successfully to MongoDB Databases: - admin - config - local Connection closed
⚠️

Common Pitfalls

Common mistakes when connecting to MongoDB in Node.js include:

  • Not awaiting client.connect(), which causes operations to fail because the connection is not ready.
  • Using an incorrect or malformed connection string URI.
  • Forgetting to close the connection with client.close(), which can cause resource leaks.
  • Not handling errors with try/catch around async calls.
javascript
import { MongoClient } from 'mongodb';

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

// Wrong: Not awaiting connect
client.connect();

// Right: Await connect inside async function
async function run() {
  try {
    await client.connect();
    // operations
  } finally {
    await client.close();
  }
}

run().catch(console.error);
📊

Quick Reference

Tips for connecting to MongoDB in Node.js:

  • Use the official mongodb package from npm.
  • Always await client.connect() before database operations.
  • Use try/catch to handle connection errors gracefully.
  • Close the connection with client.close() when done.
  • Store your MongoDB URI securely, never hardcode sensitive credentials.

Key Takeaways

Use the official mongodb package and create a MongoClient with your connection URI.
Always await client.connect() before performing database operations.
Handle errors with try/catch to avoid crashes.
Close the connection with client.close() to free resources.
Keep your connection string secure and never expose credentials in code.