10 / 12

How to connect to mongoDB database using in node js?

Difficulty: 4/10
connection string, connection pooling, error handling

We can connect to mongoDB instance using either mongodb node js package or mongoose.

mongodb package:
Mongoose:

Scenario Questions

0-2 years experience

  1. 1We have a simple Node.js script that needs to read a user document from MongoDB. Walk me through the code you'd write to establish the connection and fetch that document.
  2. 2If the MongoDB server is down when your script starts, what will happen and how would you handle that situation in your connection logic?

2-5 years experience

  1. 1You're adding a new feature that writes logs to MongoDB using the native driver, but the rest of the codebase uses Mongoose. How would you decide which library to use and what changes would you make to the connection handling?
  2. 2During testing you see intermittent 'MongoNetworkError: connection timed out' errors. How would you troubleshoot and adjust your connection configuration to reduce these failures?

5-8 years experience

  1. 1Our service runs on multiple instances behind a load balancer, and each instance opens its own MongoDB connection pool. What are the implications for connection limits and latency, and how would you configure the pool to handle high traffic?
  2. 2We need to support graceful shutdown of the Node.js process without losing in‑flight writes to MongoDB. Describe the steps you would implement to ensure connections are closed safely.

8+ years experience

  1. 1The company is migrating from a monolith to a set of microservices, each with its own MongoDB connection. What architectural patterns would you adopt to manage connection pooling, credentials, and schema versioning across services?
  2. 2We have legacy code that uses the MongoDB driver with callbacks, and new code uses async/await with Mongoose. How would you refactor the connection layer to maintain consistency, testability, and performance at scale?

Follow-up Questions

  • Can you sketch the exact code you would use to open and close the connection?
  • What is the default connection pool size and how would you change it?
  • How would you expose connection health metrics in production?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.