How to fix MongoNotConnectedError: Client must be connected before running operations in MongoDB

MongoDBBEGINNERHIGHUpdated Dec 18, 2025· 174 views

This error occurs when you attempt to perform database operations without establishing a connection first. The MongoDB client requires an explicit connection before executing any queries or commands.

Quick fix

Fixes MongoNotConnectedError: Client must be connected before running operations

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

const client = new MongoClient(uri);

async function run() {
  try {
    // Connect to MongoDB - MUST await this
    await client.connect();

    // Now safe to use the database
    const db = client.db('myDatabase');
    const collection = db.collection('myCollection');

    const result = await collection.findOne({ _id: 1 });
    console.log(result);
  } finally {
    await client.close();
  }
}

run().catch(console.error);
  1. Ensure you call and await client.connect()
  2. Create a connection singleton pattern
  3. Initialize connection before starting server
  4. Handle serverless environments properly
mongodb — error
const { MongoClient } = require('mongodb');
const client = new MongoClient(uri);
async function run() {
try {
// Connect to MongoDB - MUST await this
await client.connect();
// Now safe to use the database
const db = client.db('myDatabase');
const collection = db.collection('myCollection');
const result = await collection.findOne({ _id: 1 });
console.log(result);
} finally {
await client.close();
}
}
run().catch(console.error);
MongoNotConnectedError: Client must be connected before running operations

What this error means

The MongoNotConnectedError indicates that your application is trying to interact with MongoDB (queries, inserts, updates, etc.) before the database client has successfully connected to the server. This is a common issue in asynchronous Node.js applications where connection timing isn't properly managed. The MongoDB Node.js driver requires that you call and await the connect() method before performing any database operations. If you try to execute queries before the connection is established, the driver throws this error to prevent undefined behavior. This error is particularly common when using the native MongoDB driver directly (not through Mongoose), where connection management is more explicit. It typically occurs during application startup or in serverless environments where connections aren't persisted.

Typical symptoms

  • Application crashes immediately when trying to access database
  • Error thrown on the first database query after application start
  • Intermittent failures in serverless functions or API routes
  • Tests fail with connection errors despite valid connection string
  • Operations work sometimes but fail on cold starts

Common causes

  1. Attempting database operations before awaiting client.connect()
  2. Not calling client.connect() at all in the application initialization
  3. Connection logic runs after database queries in execution order
  4. Missing await keyword on asynchronous connection call
  5. Calling MongoClient.connect() repeatedly instead of reusing connection
  6. Connection closed prematurely before operations complete
  7. Using client.db() before connection is established

How to fix "MongoNotConnectedError: Client must be connected before running operations"

1Ensure you call and await client.connect()

Make sure you're explicitly connecting to MongoDB and waiting for the connection to complete before performing operations:

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

const client = new MongoClient(uri);

async function run() {
  try {
    // Connect to MongoDB - MUST await this
    await client.connect();

    // Now safe to use the database
    const db = client.db('myDatabase');
    const collection = db.collection('myCollection');

    const result = await collection.findOne({ _id: 1 });
    console.log(result);
  } finally {
    await client.close();
  }
}

run().catch(console.error);

The key is the await client.connect() line - without this, subsequent operations will fail.

2Create a connection singleton pattern

Instead of creating new connections throughout your app, establish one connection and reuse it:

javascript
// db.js - Connection singleton
const { MongoClient } = require('mongodb');

let client = null;
let clientPromise = null;

async function getClient() {
  if (client) {
    return client;
  }

  if (!clientPromise) {
    const uri = process.env.MONGODB_URI;
    clientPromise = MongoClient.connect(uri);
  }

  client = await clientPromise;
  return client;
}

async function getDb(dbName = 'myDatabase') {
  const client = await getClient();
  return client.db(dbName);
}

module.exports = { getClient, getDb };

Then use it in your application:

javascript
const { getDb } = require('./db');

async function findUser(userId) {
  const db = await getDb();
  return db.collection('users').findOne({ _id: userId });
}
3Initialize connection before starting server

In Express or other frameworks, connect to MongoDB before listening for requests:

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

const app = express();
const uri = process.env.MONGODB_URI;
const client = new MongoClient(uri);

async function startServer() {
  try {
    // Connect first
    await client.connect();
    console.log('Connected to MongoDB');

    // Attach client to app for route handlers
    app.locals.db = client.db('myDatabase');

    // Now start server
    app.listen(3000, () => {
      console.log('Server running on port 3000');
    });
  } catch (error) {
    console.error('Failed to start server:', error);
    process.exit(1);
  }
}

startServer();
4Handle serverless environments properly

In serverless functions (AWS Lambda, Vercel, Netlify), reuse connections across invocations:

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

// Connection cached outside handler
let cachedClient = null;

async function connectToDatabase() {
  if (cachedClient) {
    return cachedClient;
  }

  const client = await MongoClient.connect(process.env.MONGODB_URI);
  cachedClient = client;
  return client;
}

exports.handler = async (event) => {
  const client = await connectToDatabase();
  const db = client.db('myDatabase');

  const result = await db.collection('items').find({}).toArray();

  return {
    statusCode: 200,
    body: JSON.stringify(result),
  };
};

Note: Don't close the connection in serverless functions - let the execution environment manage it.

5Add connection error handling

Implement proper error handling around connection attempts:

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

async function connectWithRetry(uri, retries = 5) {
  for (let i = 0; i < retries; i++) {
    try {
      const client = await MongoClient.connect(uri, {
        serverSelectionTimeoutMS: 5000,
      });
      console.log('Successfully connected to MongoDB');
      return client;
    } catch (error) {
      console.error(`Connection attempt ${i + 1} failed:`, error.message);

      if (i === retries - 1) {
        throw new Error('Failed to connect to MongoDB after multiple retries');
      }

      // Wait before retrying
      await new Promise(resolve => setTimeout(resolve, 2000));
    }
  }
}

Advanced notes

MongoDB Driver Version Differences:

In MongoDB Node.js driver v5+, the driver will automatically call connect() when you perform operations, but this behavior can still lead to race conditions. It's recommended to explicitly call connect() for predictable behavior.

Connection Pooling:

MongoClient maintains an internal connection pool by default. You should NOT call connect() multiple times - create one client instance and reuse it. The maxPoolSize option (default 100) controls concurrent operations.

Mongoose vs Native Driver:

If using Mongoose, connection management is different. Mongoose handles connections automatically when you define models, but you should still wait for the connection:

javascript
const mongoose = require('mongoose');

await mongoose.connect(uri);
// OR with event listeners
mongoose.connection.on('connected', () => {
  console.log('Mongoose connected');
});

Testing Considerations:

In test environments using mongodb-memory-server or Jest, ensure you await connections in beforeAll() hooks:

javascript
beforeAll(async () => {
  await client.connect();
});

afterAll(async () => {
  await client.close();
});

Connection Health Checks:

Implement health checks to verify connection status:

javascript
async function checkConnection(client) {
  try {
    await client.db('admin').command({ ping: 1 });
    return true;
  } catch (error) {
    return false;
  }
}

Frequently asked questions

What does "MongoNotConnectedError: Client must be connected before running operat" mean?
) before the database client has successfully connected to the server. js applications where connection timing isn't properly managed. js driver requires that you call and await the connect() method before performing any database operations.
How do I fix "MongoNotConnectedError: Client must be connected before running operat"?
This error occurs when you attempt to perform database operations without establishing a connection first. The MongoDB client requires an explicit connection before executing any queries or commands.
What causes "MongoNotConnectedError: Client must be connected before running operat"?
Attempting database operations before awaiting client.connect() Not calling client.connect() at all in the application initialization Connection logic runs after database queries in execution order
Is the "MongoNotConnectedError: Client must be connected before running operat" error serious?
Yes. This is a high-severity error that usually blocks work until it is fixed, but the steps above resolve it.

Official resources & further reading