Solution & Challenge: Connecting to Atlas · MongoDB

Ch 1 · MongoDB Atlas and Cloud Deployment — card 4 of 4.

Check your connection code against the worked solution, which connects, pings the server, prints a message and always closes the client. The challenge is much bigger: build a complete app on Atlas with a proper database user and network access, an Express.js REST API offering create, read, update and delete endpoints, and sensible error handling with connection pooling.

const { MongoClient } = require("mongodb");
const uri = "mongodb+srv://<username>:<password>@<cluster-url>/?retryWrites=true&w=majority";
async function run() {
  const client = new MongoClient(uri);
  try {
    await client.connect();
    await client.db("admin").command({ ping: 1 });
    console.log("Connected!");
  } finally {
    await client.close();
  }
}
run();