Lesson 27 +10 XP

The Node.js Driver

The Node.js Driver

Let's connect to MongoDB from a Node.js application using the official mongodb package.

Install

npm install mongodb

Connect and read

const { MongoClient } = require("mongodb");

const uri = "<Your Connection String>";
const client = new MongoClient(uri);

async function run() {
  try {
    await client.connect();
    const db = client.db("sample_mflix");
    const collection = db.collection("movies");

    // Find the first document in the collection
    const first = await collection.findOne();
    console.log(first);
  } finally {
    // Always close the connection
    await client.close();
  }
}

run().catch(console.error);

Run it with node index.js.

The connection string

mongodb+srv://<username>:<password>@<cluster>.mongodb.net/<dbname>?retryWrites=true&w=majority

Replace <username>, <password>, and <cluster> with values from Atlas (Database → Connect → Connect your application).

The pattern

  1. new MongoClient(uri) - create a client.
  2. client.connect() - connect.
  3. client.db(name) - pick a database.
  4. db.collection(name) - pick a collection.
  5. Work with the collection, then client.close() in a finally block.

Everything is async

Driver methods return Promises, so you use async/await.

TL;DR

  • Install mongodb with npm.
  • Connect via MongoClient + Atlas connection string.
  • Always close the client in finally; methods are async.