Bird
Raised Fist0
Node.jsframework~20 mins

MongoDB connection with mongodb driver in Node.js - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
MongoDB Connection Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
What is the output of this MongoDB connection code?

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?

Node.js
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();
AAn error because the connection string is missing credentials
BAn array of database names like ['admin', 'local', 'test']
CAn empty array [] because no databases exist
DA TypeError because listDatabases is not a function
Attempts:
2 left
💡 Hint

Think about what listDatabases() returns and what map(db => db.name) does.

📝 Syntax
intermediate
2:00remaining
Which option correctly creates a MongoClient instance to connect to a MongoDB Atlas cluster?

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?

Aconst client = new MongoClient('mongodb+srv://user:pass@cluster0.mongodb.net', { useNewUrlParser: true });
Bconst client = new MongoClient('mongodb://user:pass@cluster0.mongodb.net');
Cconst client = new MongoClient('mongodb+srv://user:pass@cluster0.mongodb.net', true);
Dconst client = new MongoClient('mongodb+srv://user:pass@cluster0.mongodb.net');
Attempts:
2 left
💡 Hint

Remember the correct URI scheme for Atlas and the constructor signature.

❓ optimization
advanced
2:00remaining
How to optimize MongoDB connection reuse in a Node.js app?

You have a Node.js app that connects to MongoDB on every request, causing delays. Which approach best optimizes connection reuse?

ACreate a single <code>MongoClient</code> instance and reuse it across requests
BCreate a new <code>MongoClient</code> instance for each request and close it after
CUse <code>MongoClient.connect()</code> inside each request handler without closing
DUse a global variable to store the connection string and create clients as needed
Attempts:
2 left
💡 Hint

Think about connection overhead and resource management.

🔧 Debug
advanced
2:00remaining
Why does this MongoDB connection code throw a timeout error?

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();
AThe hostname 'invalidhost' does not resolve, causing connection timeout
BThe connection string is missing username and password, causing timeout
CThe port 27017 is blocked by firewall, causing timeout
DThe MongoClient constructor is missing options, causing timeout
Attempts:
2 left
💡 Hint

Check if the hostname is reachable.

🧠 Conceptual
expert
2:00remaining
What is the role of the useUnifiedTopology option in MongoClient?

In older versions of the mongodb driver, the useUnifiedTopology option was recommended. What does enabling this option do?

AForces the driver to use legacy connection methods for compatibility
BDisables connection pooling to reduce resource usage
CEnables the new unified topology layer that improves server discovery and monitoring
DAutomatically retries failed operations without user intervention
Attempts:
2 left
💡 Hint

Think about how the driver manages connections and monitors servers.

Practice

(1/5)
1. What is the main purpose of using MongoClient from the mongodb package in Node.js?
easy
A. To start a web server
B. To create a new database schema
C. To connect to a MongoDB database server
D. To run SQL queries on MongoDB

Solution

  1. Step 1: Understand MongoClient's role

    MongoClient is a class used to establish a connection to a MongoDB server from Node.js.
  2. Step 2: Identify the correct purpose

    It does not create schemas or run SQL queries; it only manages connections to MongoDB.
  3. Final Answer:

    To connect to a MongoDB database server -> Option C
  4. Quick Check:

    MongoClient connects to MongoDB [OK]
Hint: MongoClient is for connecting to MongoDB servers [OK]
Common Mistakes:
  • Confusing MongoClient with schema creation tools
  • Thinking MongoClient runs SQL queries
  • Assuming MongoClient starts web servers
2. Which of the following is the correct way to import MongoClient from the mongodb package in Node.js?
easy
A. const { MongoClient } = require('mongodb');
B. import MongoClient from 'mongodb';
C. const MongoClient = require('mongodb');
D. import { MongoClient } from 'mongodb';

Solution

  1. Step 1: Identify Node.js import syntax

    In Node.js with CommonJS, destructuring import uses const { MongoClient } = require('mongodb');.
  2. Step 2: Check other options

    const MongoClient = require('mongodb'); imports the entire module object, not the MongoClient class; import MongoClient from 'mongodb'; is ES module default import (incorrect here); import { MongoClient } from 'mongodb'; is ES module named import (valid only in ES modules).
  3. Final Answer:

    const { MongoClient } = require('mongodb'); -> Option A
  4. Quick Check:

    Destructured require syntax = const { MongoClient } = require('mongodb'); [OK]
Hint: Use destructuring with require for MongoClient in Node.js [OK]
Common Mistakes:
  • Using default import syntax in CommonJS
  • Requiring the module without accessing .MongoClient
  • Mixing ES module and CommonJS syntax
3. What will be the output of the following code snippet if the MongoDB URI is correct and the connection is successful?
const { MongoClient } = require('mongodb');
async function run() {
  const client = new MongoClient('mongodb://localhost:27017');
  await client.connect();
  console.log('Connected successfully to server');
  await client.close();
}
run();
medium
A. Error: MongoClient is not defined
B. No output
C. SyntaxError: await is only valid in async function
D. Connected successfully to server

Solution

  1. Step 1: Analyze the async function and connection

    The function run is async, creates a MongoClient, connects, logs success, then closes.
  2. Step 2: Check for errors or output

    Since URI is correct and await is used properly inside async function, it logs the success message.
  3. Final Answer:

    Connected successfully to server -> Option D
  4. Quick Check:

    Successful connect logs message [OK]
Hint: Async function with await logs success message [OK]
Common Mistakes:
  • Using await outside async function
  • Not calling client.connect() before logging
  • Forgetting to close the client
4. Identify the error in the following code snippet that tries to connect to MongoDB:
const { MongoClient } = require('mongodb');
const client = new MongoClient('mongodb://localhost:27017');
client.connect();
console.log('Connected');
client.close();
medium
A. Incorrect MongoDB URI format
B. Missing async/await for connect and close methods
C. MongoClient is not imported correctly
D. console.log syntax error

Solution

  1. Step 1: Check usage of connect and close

    Both connect() and close() return promises and must be awaited or handled asynchronously.
  2. Step 2: Identify missing async/await

    The code calls these methods without await or then, so connection may not complete before logging or closing.
  3. Final Answer:

    Missing async/await for connect and close methods -> Option B
  4. Quick Check:

    Async methods need await [OK]
Hint: Always await connect() and close() in async functions [OK]
Common Mistakes:
  • Calling async methods without await
  • Assuming connect() is synchronous
  • Not wrapping calls in async function
5. You want to connect to a MongoDB server using the mongodb driver in Node.js and perform a simple query to find all documents in the users collection. Which of the following code snippets correctly connects, queries, and closes the connection?
hard
A. const { MongoClient } = require('mongodb'); async function run() { const client = new MongoClient('mongodb://localhost:27017'); await client.connect(); const db = client.db('testdb'); const users = await db.collection('users').find().toArray(); console.log(users); await client.close(); } run();
B. const { MongoClient } = require('mongodb'); const client = new MongoClient('mongodb://localhost:27017'); const db = client.db('testdb'); const users = db.collection('users').find(); console.log(users); client.close();
C. import { MongoClient } from 'mongodb'; const client = new MongoClient('mongodb://localhost:27017'); await client.connect(); const users = client.db('testdb').collection('users').find().toArray(); console.log(users); await client.close();
D. const MongoClient = require('mongodb'); const client = new MongoClient('mongodb://localhost:27017'); client.connect(); const users = client.db('testdb').collection('users').find().toArray(); console.log(users); client.close();

Solution

  1. Step 1: Check for proper async/await usage

    const { MongoClient } = require('mongodb'); async function run() { const client = new MongoClient('mongodb://localhost:27017'); await client.connect(); const db = client.db('testdb'); const users = await db.collection('users').find().toArray(); console.log(users); await client.close(); } run(); uses async function with await for connect, query, and close, ensuring proper sequence.
  2. Step 2: Validate correct import and method calls

    const { MongoClient } = require('mongodb'); async function run() { const client = new MongoClient('mongodb://localhost:27017'); await client.connect(); const db = client.db('testdb'); const users = await db.collection('users').find().toArray(); console.log(users); await client.close(); } run(); correctly imports MongoClient, connects, queries with toArray(), logs, and closes connection.
  3. Final Answer:

    Uses destructured import, async function, await connect(), find().toArray(), await close() -> Option A
  4. Quick Check:

    Async connect, query, close with await = const { MongoClient } = require('mongodb'); async function run() { const client = new MongoClient('mongodb://localhost:27017'); await client.connect(); const db = client.db('testdb'); const users = await db.collection('users').find().toArray(); console.log(users); await client.close(); } run(); [OK]
Hint: Use async/await for connect, query, and close in sequence [OK]
Common Mistakes:
  • Not awaiting connect or query results
  • Using incorrect import syntax
  • Calling methods without async context
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard