Node.js Quick Start

Connect to DocumentDB from Node.js using the official MongoDB driver.

Prerequisites

  • Node.js 18 or later
  • npm
  • Docker
  • Basic familiarity with JavaScript

Start DocumentDB Local

docker run -dt --name documentdb \
  -p 10260:10260 \
  ghcr.io/documentdb/documentdb/documentdb-local:latest \
  --username <YOUR_USERNAME> \
  --password <YOUR_PASSWORD>

Replace <YOUR_USERNAME> and <YOUR_PASSWORD> with your own credentials.

DocumentDB Local uses a self-signed certificate by default, so the quickest local Node.js connection uses tlsAllowInvalidCertificates=true.

Create a project

mkdir my-documentdb-app
cd my-documentdb-app
npm init -y
npm install mongodb

Connect and run your first queries

Create an index.js file:

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

const uri =
  "mongodb://<YOUR_USERNAME>:<YOUR_PASSWORD>@localhost:10260/" +
  "?authSource=admin&tls=true&tlsAllowInvalidCertificates=true&directConnection=true";

async function main() {
  const client = new MongoClient(uri);

  try {
    await client.connect();

    const db = client.db("quickstart");
    await db.command({ ping: 1 });

    const movies = db.collection("movies");

    await movies.insertMany([
      { title: "The Matrix", year: 1999, genres: ["sci-fi", "action"] },
      { title: "Dune", year: 2021, genres: ["sci-fi", "adventure"] },
      { title: "Arrival", year: 2016, genres: ["sci-fi", "drama"] }
    ]);

    await movies.createIndex({ title: 1 });

    const recentMovies = await movies
      .find(
        { year: { $gte: 2000 } },
        { projection: { _id: 0, title: 1, year: 1 } }
      )
      .sort({ year: -1 })
      .toArray();

    console.log("Connected to DocumentDB");
    console.log(recentMovies);
  } finally {
    await client.close();
  }
}

main().catch(console.error);

Run the script:

node index.js

Connect with a trusted local certificate instead

If you want certificate validation instead of tlsAllowInvalidCertificates=true, copy the generated certificate from the container and point the driver at it.

docker cp documentdb:/home/documentdb/gateway/pg_documentdb_gw/cert.pem ~/documentdb-cert.pem
const uri =
  "mongodb://<YOUR_USERNAME>:<YOUR_PASSWORD>@localhost:10260/" +
  "?authSource=admin&tls=true&tlsCAFile=/absolute/path/documentdb-cert.pem&directConnection=true";