npm 2,036 install mongodb adds 12 packages and needs no build step. Version 7.6.0, published 24 August 2026, is current at the time of writing and requires Node.js 20.19.0 2,131 or newer. Three of those packages are direct dependencies — bson, mongodb-connection-string-url and @mongodb-js/saslprep; compression, Kerberos, AWS 24 IAM authentication and field level encryption are optional peer dependencies, installed only if used.
MongoClient takes the URI from Connection Strings plus options. One client is a deployment, not a socket: it discovers the topology, monitors every member, and owns the connection pool.
import { MongoClient } from "mongodb";
const uri = "mongodb://127.0.0.1:28111/?directConnection=true&appName=bookshelf-api";
const client = new MongoClient(uri, { serverSelectionTimeoutMS: 3000 });
await client.connect();
const admin = client.db().admin();
console.log("server", (await admin.serverInfo()).version, "topology",
client.topology.description.type, "ping", (await admin.command({ ping: 1 })).ok);
await client.close();
const bad = new MongoClient("mongodb://127.0.0.1:28999/?serverSelectionTimeoutMS=2000");
try {
await bad.db("test").command({ ping: 1 });
} catch (err) {
console.log(err.constructor.name, "|", err.message.split("\n")[0], "| reason:",
err.reason?.type, [...(err.reason?.servers?.keys() ?? [])]);
} finally { await bad.close(); }server 8.3.11 topology Single ping 1 MongoServerSelectionError | connect ECONNREFUSED 127.0.0.1:28999 | reason: Unknown [ '127.0.0.1:28999' ]
topology is Single because directConnection=true tells the driver to treat the host as one server; drop that option against a replica set and it becomes ReplicaSetWithPrimary. The failure is not an ECONNREFUSED thrown by a socket: it is a MongoServerSelectionError raised after serverSelectionTimeoutMS expired with no usable server, carrying the socket error as its reason. A wrong port, a stopped mongod and a firewall therefore look identical to your code, and the default 30-second timeout is far too long for a health check. connect() is optional — any operation connects on demand — but calling it at startup proves credentials and network before the first request arrives.