B · Node.js application code

Use MongoDB cursors and connection pools deliberately

A database call can be correct in isolation and still overwhelm an API when it loads an unbounded result set or opens a client for every request. Follow a paged order-history request from the filter through cursor cleanup.

Original study guide · Reviewed against official documentation on November 17, 2026

The situation: an order-history endpoint

An account page needs the most recent 25 orders for one customer. The endpoint should return a predictable page, keep application memory bounded, and work while many users make requests at the same time.

const cursor = orders.find(
  { customerId, status: "paid" },
  {
    projection: { _id: 1, placedAt: 1, total: 1 },
    sort: { placedAt: -1, _id: -1 },
    limit: 25
  }
);

try {
  for await (const order of cursor) {
    await writeOrderToResponse(order);
  }
} finally {
  await cursor.close();
}

The sort includes _id as a tie-breaker. Two orders may have the same placedAt; without a second field, their relative order can shift between requests. Stable ordering matters when the next page is defined relative to the last item the client saw.

A cursor is a plan to read, not an array

In the Node.js driver, find() returns a cursor synchronously. It does not return a promise containing every matching document. await collection.find(...) therefore does not consume the cursor. Documents arrive as the cursor is iterated, for example with for await...of, or when a bounded cursor is converted with toArray().

toArray() is convenient when a result is deliberately small and has a limit. It can be a memory problem when the query is unbounded or when documents are large. For exports and batch jobs, iteration lets the application process each document and discard it before reading the next one. Always set a practical limit or stream according to the task.

Reuse the client across requests

Create one MongoClient during application startup, connect it, and let incoming requests use its pools. Each client manages pools for the servers in the deployment; operations borrow a connection and return it for reuse. Constructing a client inside every route handler defeats that pooling strategy and creates connection churn under load.

const client = new MongoClient(uri);
await client.connect();
const orders = client.db("shop").collection("orders");

// Route handlers use `orders` without making a new MongoClient.
// During graceful process shutdown:
await client.close();

The pool is not a reason to choose an arbitrarily large size. Start with driver defaults, measure wait time and concurrency, then tune the pool for the deployment and workload. A single process may still need backpressure if many expensive reads run at once.

Tempting answers that fail

Calling toArray() without a limit may return far more than the endpoint can send. Opening a fresh client for each request creates pools repeatedly rather than reusing them. Returning a cursor from an HTTP handler after the response has ended also leaves ownership unclear; consume it inside the request or define a streaming response lifecycle explicitly.

For dependent writes, await the operation whose result matters. If several operations form a transaction, start a session and pass that same session to each operation. A session does not automatically attach itself to every collection call.

Check your understanding

Question: Why does await orders.find({ customerId }) still not give the route an array of orders?

Answer: find() creates and returns a cursor; the driver retrieves result batches as that cursor is consumed. Use a bounded toArray() for a small finite result or iterate the cursor when the result may be larger.

Further reading