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.
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.
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));
}
}
}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;
}
}DivergentArrayError: For your own good, using document.save() to update an array which was selected using an $elemMatch projection will not work
How to fix "DivergentArrayError: For your own good, using document.save() to update an array which was selected using an $elemMatch projection will not work" in MongoDB
MongoServerError: bad auth : authentication failed
How to fix "MongoServerError: bad auth : authentication failed" in MongoDB
CannotCreateIndex: Cannot create index
CannotCreateIndex: Cannot create index
StaleShardVersion: shard version mismatch
How to fix "StaleShardVersion: shard version mismatch" in MongoDB
MongoOperationTimeoutError: Operation timed out
How to fix "MongoOperationTimeoutError: Operation timed out" in MongoDB