MongoDB / Intermediate: aggregation and application contracts / Lesson 11
Drivers, connections and security boundaries
Use supported clients with bounded pools, explicit identity and transport protection. Distinguish Atlas network admission from database authentication and authorization.
On this page
Lesson goals
- Explain URI, SRV, TLS and authSource responsibilities.
- Design input, pool and privilege boundaries without broad defaults.
Server, driver and runtime versions are independent
A driver translates language values into BSON, manages server selection and often maintains a connection pool. Compatibility depends on the server release, driver release and language runtime, so a shared MongoDB product name is insufficient evidence. Reuse a properly managed application client rather than constructing one per request, while respecting documented lifecycle and thread-safety rules. Bound concurrency and timeouts from service requirements. A large pool does not create more database capacity, and connection failures should not trigger an unlimited reconnect or request retry storm.
Read a URI as configuration, not a credential container
This illustrative SRV URI uses a reserved example hostname and contains no credentials. In the Node.js driver, MongoClient construction creates a client object, while operations or explicit connect can initiate network work. This fragment is never executed here. SRV discovery requires appropriate DNS records and support, and mongodb+srv enables TLS by default unless explicitly overridden. Do not disable certificate checks to make a name or trust-chain problem disappear. Obtain the actual approved Atlas or self-managed connection configuration through the normal secret and deployment process.
// Node.js driver illustration only; requires a compatible installed driver.
const { MongoClient } = require('mongodb');
const client = new MongoClient('mongodb+srv://cluster.example.test/quay_lab', {
maxPoolSize: 10, serverSelectionTimeoutMS: 5000
});
// No connect() or database operation is executed in this illustration.
Ten connections and five seconds are teaching values, not universal production recommendations. No credentials or resolvable service are supplied.
Network admission is not a database role
Atlas access controls include deployment networking and database users; an Atlas project account is not automatically the database identity used by a driver. Self-managed installations need their own reviewed authentication, authorization and TLS configuration. authSource identifies where the database user authenticates, not necessarily the application database being queried. Roles determine permitted operations after authentication. Keep runtime, migration, monitoring and backup identities separate, and avoid broad administrator roles for request handling. Feature availability and management interfaces can differ across Community, Enterprise and Atlas deployment tiers.
Validate values and reject arbitrary operators
The safe local pattern builds a known filter from validated scalar values rather than accepting a request body as the complete query. The literal object below is not sent to a server; it illustrates the expected exact shape. An attacker-controlled object such as {$ne:null} should not be treated as an ordinary account string. Parameter handling in a document driver is not SQL string binding, so define allowed fields, operators, types and tenant scope explicitly. Projection and validation do not replace authorization.
const request = { tenantId: 'training-a', trackingCode: 'PK-101' };
if (typeof request.tenantId !== 'string' || typeof request.trackingCode !== 'string') {
throw new TypeError('scalar strings required');
}
const filter = { tenantId: request.tenantId, trackingCode: request.trackingCode };
printjson(filter);
{ tenantId: "training-a", trackingCode: "PK-101" }
The filter structure is application-owned; only validated values come from the request.
Classify failures before retrying
A server-selection timeout can reflect DNS, topology, TLS, reachability or role-specific discovery constraints; it is not a complete diagnosis of a slow query. Authentication failure and authorization failure require different evidence. Retryable writes and transaction callbacks follow driver-supported semantics and do not make arbitrary business operations idempotent. Preserve structured error codes and labels without logging secrets. Close clients during orderly application shutdown and clean up cursors and sessions; per-request close/recreate cycles undermine pooling. Revalidate the compatibility matrix when upgrading the driver or runtime.
Common errors and fixes
MongoServerSelectionError
- Why it happens
- No eligible server was selected within the configured budget.
- How to fix it
- Inspect topology, DNS, TLS and reachability evidence before changing the budget.
- Prevent it next time
- Test the intended client environment and bound reconnect behavior.
Authentication failed (18)
- Why it happens
- Credentials, mechanism or authSource does not match the database user.
- How to fix it
- Review approved provisioning without weakening TLS or granting broad roles.
- Prevent it next time
- Separate Atlas account access from database user configuration.
A request object changes query meaning
- Why it happens
- Untrusted operators were accepted as query structure.
- How to fix it
- Allowlist structure and validate scalar input types.
- Prevent it next time
- Test operator-object injection and tenant-scope preservation.
Check your understanding
1. Does a successful Atlas console login prove the application database password and role are correct?
Show worked solution
No. Project access and database authentication are separate layers, as are network admission and TLS. Verify the intended database user, authSource, mechanism and scoped role using the approved connection process. Do not respond by assigning a project account as a database credential or opening access from every address. Preserve the exact error stage to avoid treating all failures as bad passwords.
2. A developer creates and closes MongoClient for every HTTP request. What should be reviewed?
Show worked solution
Review driver lifecycle guidance and use a bounded reusable client/pool appropriate to the application runtime. Per-request construction adds discovery, TLS and connection overhead and can amplify bursts. Measure workload concurrency, timeouts and server capacity before choosing limits. Reuse does not mean unlimited parallel operations or skipping shutdown cleanup; both resource budget and lifecycle remain explicit contracts.
Key takeaways
- Connection, authentication, authorization and query structure are separate boundaries.
- Use compatible drivers and bounded reusable clients without publishing secrets.