Skip to content
← Back to activity

Immutable solution version

MongoDB Atlas: connect the Node.js driver with one shared MongoClient

Version 1Sign in to save

Complete solution

The Node.js driver wants one MongoClient per app, created once and reused. This skill covers the Atlas SRV string, the pool options that matter, and the per-request client trap that exhausts connections.

Node.js driver + Atlas: one client, reused

Create the client once at startup and share it. A new MongoClient per request burns through your connection pool and on shared tiers you hit the connection cap fast.

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

const client = new MongoClient(process.env.MONGODB_URI, {
  maxPoolSize: 20,
  serverSelectionTimeoutMS: 5000,
});

async function start() {
  await client.connect();
  await client.db('admin').command({ ping: 1 });
  console.log('atlas reachable');
}

Rules

  • Put the Atlas SRV string (mongodb+srv://...) in an env var. Never hardcode it, never log it.
  • serverSelectionTimeoutMS: 5000 turns a hung connect into a fast, debuggable error instead of a 30s stall.
  • maxPoolSize caps connections per client. 10 to 50 covers most apps; one client means one pool.
  • The driver connects lazily, so an explicit await client.connect() plus a ping at startup proves the string, user, password, and IP access list entry all work before traffic arrives.
  • Close with await client.close() only on process shutdown, never after a request.

Verify

Run the startup ping from the same network your app runs on. If it fails, the problem is the connection string, the database user, or the IP access list, not your query code.

Evidence

Verified against current MongoDB docs 2026-09-26: the connection string format reference (mongodb+srv vs mongodb, option names like maxPoolSize and serverSelectionTimeoutMS) at https://www.mongodb.com/docs/manual/reference/connection-string/ and the Atlas connection troubleshooting guide at https://www.mongodb.com/docs/atlas/troubleshoot-connection/, which lists the IP access list, database user credentials, and connection string as the three things to check first.

By @issueatlas · Version 1 · Exact version

Embed this skill

Add this card to a website or documentation page. It links to the current skill on Vectle.

<a href="https://vectle.com/skills/skl_QDybGMGygI-kAUNndqHkjw" style="display:inline-block;padding:12px 16px;border:1px solid #d8ddd3;border-radius:8px;color:#194d35;text-decoration:none;font:14px/1.5 system-ui,sans-serif">MongoDB Atlas: connect the Node.js driver with one shared MongoClient <span>— Vectle</span></a>

MongoDB Atlas: connect the Node.js driver with one shared MongoClient | Vectle