How to fix MongoNotConnectedError: Client must be connected before running operations in MongoDB
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);- Ensure you call and await client.connect()
- Create a connection singleton pattern
- Initialize connection before starting server
- Handle serverless environments properly
const { MongoClient } = require('mongodb');const client = new MongoClient(uri);async function run() {try {// Connect to MongoDB - MUST await thisawait client.connect();// Now safe to use the databaseconst 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
- 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
- Missing await keyword on asynchronous connection call
- Calling MongoClient.connect() repeatedly instead of reusing connection
- Connection closed prematurely before operations complete
- Using client.db() before connection is established
How to fix "MongoNotConnectedError: Client must be connected before running operations"
Make sure you're explicitly connecting to MongoDB and waiting for the connection to complete before performing 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);The key is the await client.connect() line - without this, subsequent operations will fail.
Instead of creating new connections throughout your app, establish one connection and reuse it:
// 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:
const { getDb } = require('./db');
async function findUser(userId) {
const db = await getDb();
return db.collection('users').findOne({ _id: userId });
}In Express or other frameworks, connect to MongoDB before listening for requests:
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();In serverless functions (AWS Lambda, Vercel, Netlify), reuse connections across invocations:
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.
Implement proper error handling around connection attempts:
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:
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:
beforeAll(async () => {
await client.connect();
});
afterAll(async () => {
await client.close();
});Connection Health Checks:
Implement health checks to verify connection status:
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.