Q1. How do you connect Node.js to MongoDB?
Use the official MongoDB driver or Mongoose ODM. With MongoDB driver: npm install mongodb, then:
const { MongoClient } = require('mongodb');
const client = new MongoClient('mongodb://localhost:27017');
await client.connect();
const db = client.db('mydb');
Handle connection errors and close connection properly.Q2. What is Mongoose and why use it?
Mongoose is an ODM (Object Data Modeling) library for MongoDB and Node.js. It provides a schema-based solution to model data with built-in validation, type casting, and query building. It makes MongoDB interactions more structured and easier to manage. Example:
const userSchema = new mongoose.Schema({ name: String });
const User = mongoose.model('User', userSchema);
Q3. How do you handle connection errors with MongoDB?
Use try/catch with async/await, or handle error events. With Mongoose:
mongoose.connect(uri)
.then(() => console.log('Connected'))
.catch(err => console.error('Connection error', err));
Also listen for error events after connection:
mongoose.connection.on('error', err => {
// handle error
});
Q4. What is connection pooling in MongoDB?
The MongoDB driver maintains a pool of connections to the database. By default, it has a max pool size of 100. This allows multiple operations to reuse connections efficiently without creating new connections for each request. You can configure pool size in the connection string: mongodb://localhost:27017/?maxPoolSize=50.
Q5. How do you close MongoDB connection gracefully?
For clean shutdown, close the connection when your app terminates. Listen for process signals:
process.on('SIGINT', async () => {
await client.close();
process.exit(0);
});
With Mongoose:
mongoose.connection.close()
This ensures any pending operations complete and prevents memory leaks.