Q1. How do you connect Node.js to MongoDB using the native driver?
First install the MongoDB driver:
npm install mongodbThen connect: const { MongoClient } = require('mongodb');
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const db = client.db('mydb');
console.log('Connected');
} finally {
await client.close();
}
}
run().catch(console.dir);Q2. How do you handle connection errors?
Wrap connection logic in try/catch and listen for error events:
client.on('error', (err) => {
console.error('MongoDB error:', err);
});
async function connect() {
try {
await client.connect();
} catch (err) {
console.error('Connection failed:', err);
}
}Q3. How do you use connection pooling?
The MongoDB driver uses connection pooling by default. You can configure pool size in the connection URI:
const uri = "mongodb://localhost:27017/?maxPoolSize=10";Or in MongoClient options: const client = new MongoClient(uri, { maxPoolSize: 10 });Q4. What is the difference between MongoClient and Db objects?
MongoClient represents the connection to the MongoDB server. It can be used to access multiple databases.
Db represents a specific database and is obtained via client.db().
From Db, you get Collection objects to perform CRUD operations.
The hierarchy is: MongoClient → Db → Collection.
Db represents a specific database and is obtained via client.db().
From Db, you get Collection objects to perform CRUD operations.
The hierarchy is: MongoClient → Db → Collection.
Q5. How do you close the MongoDB connection gracefully?
Call client.close() when your application shuts down. For web servers, listen for process signals:
process.on('SIGINT', async () => {
await client.close();
process.exit(0);
});