Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 70 ยท Drivers and applications

Using MongoDB from Node.js

Use MongoDB from Node.js with the official driver: MongoClient and connection pooling, CRUD with async/await, cursors, error handling and good habits.

So far you have talked to MongoDB through the shell. Real applications talk to it through a driver, a library for your language that opens connections, sends commands and turns BSON into native values. For Node.js the official driver is the mongodb package on npm. It has promise-based methods for everything you have learned: insertOne, find, updateMany, aggregate and the rest keep the names and arguments you know from mongosh, and they return promises that you await.

This lesson covers how to connect, why you create exactly one MongoClient, how the connection pool works, what the results of each operation look like, how to read results with cursors, and how to handle the errors you will actually meet. It assumes you know async/await (Async/Await in Node.js); for the surrounding ecosystem see MongoDB and Redis from Node.

A real driver needs a server, which this site does not have. The npm and driver listings are real code and are read-only. The runnable examples use a small asynchronous stand-in with the same method names and result shapes as the driver, running on an in-memory array. It is not the driver, and it implements only a handful of operators.

The life of a connection

One MongoClient Create it once when the app starts.
Pool It keeps several connections ready for you.
Reuse Every request borrows and returns one.
Close On shutdown, call client.close().
1 / 2

Installing and connecting

Install the driver into your project, then create a client with the connection string from Installing MongoDB and Using mongosh (or from Atlas, see MongoDB Atlas Overview):

Terminal
npm install mongodb
JavaScript
import { MongoClient } from "mongodb";

const client = new MongoClient(process.env.MONGODB_URI);
await client.connect();

const db = client.db("shop");
const products = db.collection("products");

Three details are worth noticing. First, the connection string comes from an environment variable and not from the source code, so the password stays out of your repository (Secrets and Config covers the habit). Second, client.db("shop") and db.collection("products") do not contact the server. They return handles, and the collection is created when you first write to it. Third, in current versions of the driver client.connect() is optional, because the client connects on first use. Calling it at startup is still good practice: a wrong password or a blocked network then fails the application immediately, with a clear error, instead of on the first user request.

The examples use ES modules (import). With CommonJS you would write const { MongoClient } = require("mongodb");.

One client per process

The most important rule of the driver: create one MongoClient and share it for the life of your process. A client is not a single connection. It owns a connection pool, background monitoring of the servers, and the logic that follows a replica set through failovers. Creating a client per request throws all of that away, adds a TLS handshake to every request and can exhaust the server's connection limit under load.

A common structure is a small module that creates the client once and exports the handles:

JavaScript
// db.js
import { MongoClient } from "mongodb";

export const client = new MongoClient(process.env.MONGODB_URI);
export const db = client.db("shop");

Every file that imports db shares the same client. In a serverless platform, where the process may live only briefly, keep the client in a module-level variable so a warm invocation reuses it.

The connection pool

By default the driver keeps up to 100 connections per server in its pool (maxPoolSize), opens them as they are needed, and closes idle ones after a while. Each operation borrows a connection, runs, and gives it back. If all connections are busy, the operation waits in a queue until one is free. Useful options go into the connection string or the client options:

JavaScript
const client = new MongoClient(uri, {
  maxPoolSize: 20,                   // upper limit of open connections per server
  minPoolSize: 2,                    // keep a few warm
  serverSelectionTimeoutMS: 5000,    // give up finding a server after 5 s
  maxIdleTimeMS: 60000               // close connections idle for a minute
});

A bigger pool is not automatically better. A server can only do so much work at once, and with many application instances maxPoolSize multiplies: 50 instances times 100 connections is 5,000 connections, which is heavy for a small cluster. Size the pool for what your workload needs and remember the total across all instances. The serverSelectionTimeoutMS setting matters because its default of 30 seconds makes a down database look like a hung application.

CRUD with async/await

Each driver method returns a promise. Inserts and updates return a small result object, and the fields mirror what you saw in the shell:

JavaScript
const one = await products.insertOne({ name: "Desk Lamp", price: 24.5 });
// { acknowledged: true, insertedId: ObjectId('...') }

const many = await products.insertMany([{ name: "Notebook" }, { name: "Stapler" }]);
// { acknowledged: true, insertedCount: 2, insertedIds: { '0': ObjectId('...'), '1': ObjectId('...') } }

const lamp = await products.findOne({ name: "Desk Lamp" });   // the document, or null

const upd = await products.updateOne({ name: "Desk Lamp" }, { $set: { price: 22 } });
// { acknowledged: true, matchedCount: 1, modifiedCount: 1, upsertedCount: 0, upsertedId: null }

const del = await products.deleteOne({ name: "Desk Lamp" });  // { acknowledged: true, deletedCount: 1 }

findOne resolves to null when nothing matches: it does not throw. Likewise updateOne on a filter that matches nothing succeeds with matchedCount: 0, so check the counts if "not found" matters to your logic. The difference between matchedCount and modifiedCount is explained in Updating Documents. findOneAndUpdate and its siblings return the document itself (or null), and the returnDocument: "after" option picks the version after the update (Upserts, Replace and findAndModify).

The _id that the driver generates is an ObjectId instance. When an id arrives as a string, for example from a URL, convert it before you query:

JavaScript
import { ObjectId } from "mongodb";

if (!ObjectId.isValid(req.params.id)) {
  return res.status(400).json({ error: "invalid id" });
}
const product = await products.findOne({ _id: new ObjectId(req.params.id) });

Querying with the string "65f1..." instead of an ObjectId finds nothing, which is a very common bug, because the types differ.

The first TryIt: CRUD with the stand-in client

This runnable version has the same shape as the driver code above. The stand-in supports equality filters and $lt, $lte, $gt, $gte, $in and $ne, the update operators $set and $inc, plus sort and limit. Change the filters, add documents, and watch the result objects.

JS CRUD with async/await

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Read the printed result objects next to the shell listings above. insertMany reports the count and the id of each inserted document, updateOne on a missing product still succeeds with matchedCount: 0, and findOneAndUpdate with returnDocument: "after" returns the changed document directly.

Reading with cursors

find() does not return an array. It returns a cursor, a handle to the server's result set. The driver fetches documents from the server in batches as you consume them. You choose how:

JavaScript
// 1. All at once: simple, but the whole result must fit in memory
const list = await products.find({ price: { $lt: 30 } }).sort({ price: 1 }).limit(50).toArray();

// 2. One at a time with for await: constant memory, best for large results
for await (const product of products.find({ stock: { $lt: 10 } })) {
  await notifyBuyer(product);
}

// 3. Manual control
const cursor = products.find();
while (await cursor.hasNext()) {
  const product = await cursor.next();
}
await cursor.close();

Creating the cursor with find() is synchronous and sends nothing. The query runs when you first read from it. sort, limit, skip and project chain on the cursor just as in the shell, so Sorting, Limiting and Skipping and Projection apply unchanged. Use toArray() only when you know the result is small: with a million documents it would load them all. Prefer a limit, a projection that returns only the fields you need, or for await.

Handling errors

Driver errors are classes, and checking the class or the code is better than parsing the message. The ones you will meet:

  • MongoServerError: the server rejected the operation. The code and codeName fields tell you why: 11000 is a duplicate key, 121 is a document validation failure.
  • MongoBulkWriteError: a bulk or insertMany operation had failures. It carries a writeErrors list and the counts that did succeed (Inserting Documents).
  • MongoServerSelectionError: the driver could not find a suitable server within serverSelectionTimeoutMS, for example because the database is down, the address is wrong or the IP is not on the access list.
  • MongoNetworkError and MongoNetworkTimeoutError: the connection failed or timed out in the middle of an operation.
JavaScript
import { MongoServerError } from "mongodb";

try {
  await users.insertOne({ _id: "[email protected]", name: "Ada" });
} catch (err) {
  if (err instanceof MongoServerError && err.code === 11000) {
    // a user with this email already exists: report it nicely
  } else {
    throw err; // unknown problem: let the caller or a global handler deal with it
  }
}

Handle the errors you can recover from (duplicates, validation) at the call site and let everything else propagate to your central error handling (Errors). Recent drivers retry single writes and reads once after a transient failure such as a primary election, because retryWrites and retryReads are on by default. A network error that still reaches your code means the retry failed too.

The second TryIt: cursors and errors

This example uses the same stand-in to show a duplicate key error handled by its class and code, the null that findOne returns for a missing document, an id check before the lookup, and both cursor styles. It uses its own copy of the stand-in so that it runs on its own.

JS Cursors, null results and duplicate keys

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The duplicate is recognized by class and code, and the application turns it into a friendly message. findOne and deleteOne on a missing document return null and deletedCount: 0 with no exception, so your code must check those values when absence matters. Both cursor styles return the same documents, but only for await keeps memory constant on large results.

The third TryIt: a pool in action

A pool limits how many operations can use the server at once. The next stand-in gives a pool two connections and starts five operations at the same moment. Operations that find no free connection wait their turn, which is exactly what the driver does. Change maxPoolSize and watch how many operations run in parallel.

JS Five operations, two connections

Press Run (or Ctrl + Enter) to see the console output here.

No output.

With two connections, three operations queue and the peak never passes two. With five, nothing waits. In a real application the same pool is shared by every request, so a slow query that holds a connection too long makes other requests wait behind it. That is why timeouts and fast queries matter more than a huge pool.

Good habits

  • Create the client once and close it on shutdown (await client.close() in your SIGTERM handler, see Graceful Shutdown). A script that forgets to close the client may never exit, because the open pool keeps the process alive.
  • Always await. A forgotten await on insertOne returns a pending promise, the next line runs too early, and errors become unhandled rejections.
  • Never build queries from raw request bodies. Passing req.body straight into a filter lets a client send operators such as { "$ne": null }. See NoSQL Injection and Safe Queries.
  • Use TypeScript generics to type documents: db.collection<Product>("products") gives you checked field names in filters and results.
  • Use sessions for transactions. client.withSession() and session.withTransaction() are covered in Multi-Document Transactions.
  • Keep data access in one module (a repository or data-access layer) so that queries, indexes and error handling live in one place instead of being scattered over route handlers.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many MongoClient instances should a typical Node.js server process create?

    A client owns a connection pool and server monitoring. Creating it per request wastes handshakes and can exhaust the server's connection limit.
  2. 2. What does collection.findOne({ name: "Piano" }) resolve to when no document matches?

    findOne resolves to null when nothing matches. Only genuine failures, such as network errors, reject the promise.
  3. 3. You call products.findOne({ _id: req.params.id }) with the string "65f1a2b3c4d5e6f708000001" and always get null. What is the likely cause?

    An ObjectId and a string with the same hex digits are different BSON types, so the equality filter does not match. Validate with ObjectId.isValid and convert.
  4. 4. Which is the best way to process a very large result set?

    Iterating the cursor fetches documents in batches and keeps memory use constant, while toArray loads everything at once.

Summary

  • The mongodb package gives you promise-based methods with the same names as the shell; results are small objects such as { acknowledged, insertedId } or { matchedCount, modifiedCount }.
  • Create one MongoClient per process; it owns a connection pool (default maxPoolSize 100), so share it and close it on shutdown.
  • findOne returns null for no match and updateOne reports matchedCount: 0; check those values when absence matters.
  • find() returns a cursor: use toArray() for small results and for await for large ones.
  • Handle MongoServerError by code (11000 duplicate key), expect MongoServerSelectionError when the cluster is unreachable, and let unknown errors propagate.
  • Convert string ids with new ObjectId(), load credentials from the environment, and never pass raw request bodies into filters.

Next, see the same ideas in Python in Using MongoDB from Python.