01 / 19

How to Connect to MongoDB server from Node.js application?

MongoDB can be connected from Node by calling the connect() method of MongoClient class.

javascript
Difficulty: 4/10
Topics: connection string, authentication, connection pooling

Scenario Questions

0-2 years experience
  1. 1

    We have a simple Node.js script that needs to read a collection from a local MongoDB. How would you establish the connection?

  2. 2

    If you forget to include the database name in the connection string, what will happen when you run a query?

  3. 3

    During startup the app crashes with a connection error. What steps do you take to handle that gracefully?

2-5 years experience
  1. 1

    Your new feature writes logs to MongoDB, but after deployment you see intermittent MongoNetworkError timeouts. How would you debug and resolve this?

  2. 2

    You need to support separate dev and prod MongoDB credentials without hard‑coding them. How would you structure the connection code?

  3. 3

    Explain why you might enable the unified topology option and what impact it has on connection handling.

5-8 years experience
  1. 1

    At high load the service opens many connections and memory usage spikes. How would you redesign the connection handling to be more efficient?

  2. 2

    Describe how you would implement a graceful shutdown that ensures all pending MongoDB operations finish before the process exits.

  3. 3

    What configuration would you choose for connection pooling and retry logic for a microservice handling thousands of requests per second?

8+ years experience
  1. 1

    Our monolith is being split into multiple services, each needing MongoDB access. What architectural pattern would you use for managing connections across services?

  2. 2

    How would you design a shared MongoDB connection library that satisfies security, observability, and versioning requirements across several teams?

  3. 3

    If we need multi‑region read/write with eventual consistency, how does that affect your connection strategy and driver options?

Follow-up Questions

  • Can you sketch the minimal code you would write?
  • What would you monitor to know the connection is healthy?
  • How would you test connection failures in CI?