Consider the following Node.js code snippet using the mongodb driver to connect to a MongoDB server and list database names. What will be printed to the console?
import { MongoClient } from 'mongodb'; async function listDatabases() { const client = new MongoClient('mongodb://localhost:27017'); try { await client.connect(); const databasesList = await client.db().admin().listDatabases(); console.log(databasesList.databases.map(db => db.name)); } finally { await client.close(); } } listDatabases();
Think about what listDatabases() returns and what map(db => db.name) does.
The listDatabases() method returns an object with a databases array. Mapping over it extracts the names, so the console prints an array of database names.
You want to connect to a MongoDB Atlas cluster with the connection string mongodb+srv://user:pass@cluster0.mongodb.net. Which code snippet correctly creates the MongoClient instance?
Remember the correct URI scheme for Atlas and the constructor signature.
The mongodb+srv scheme is required for Atlas. The MongoClient constructor takes the connection string as the first argument. Options are optional and must be an object.
You have a Node.js app that connects to MongoDB on every request, causing delays. Which approach best optimizes connection reuse?
Think about connection overhead and resource management.
Creating and closing a client for each request is expensive. Reusing a single client instance improves performance and resource usage.
Given this code snippet, why does it throw a timeout error when trying to connect?
import { MongoClient } from 'mongodb';
const client = new MongoClient('mongodb://invalidhost:27017');
async function run() {
await client.connect();
console.log('Connected');
}
run();Check if the hostname is reachable.
A non-existent hostname causes the driver to wait until the connection attempt times out.
useUnifiedTopology option in MongoClient?In older versions of the mongodb driver, the useUnifiedTopology option was recommended. What does enabling this option do?
Think about how the driver manages connections and monitors servers.
The unified topology layer provides a more robust and consistent way to handle server discovery and monitoring, improving reliability.