All sections
All sections
You are viewing the frozen documentation for v0.114-0. It is not updated and may not reflect the latest release.
View current version →Learn how to set up and use DocumentDB with Node.js using the official MongoDB Node.js driver.
Before connecting from Node.js, make sure you have a running DocumentDB instance using Docker:
# Pull the latest DocumentDB Docker image
docker pull ghcr.io/documentdb/documentdb/documentdb-local:latest
# Tag the image for convenience
docker tag ghcr.io/documentdb/documentdb/documentdb-local:latest documentdb
# Run the container with your chosen username and password
docker run -dt -p 10260:10260 --name documentdb-container documentdb --username <YOUR_USERNAME> --password <YOUR_PASSWORD>
docker image rm -f ghcr.io/documentdb/documentdb/documentdb-local:latestNote: During the transition to the Linux Foundation, Docker images may still be hosted on Microsoft's container registry. These will be migrated to the new DocumentDB organization as the transition completes.
Note: Replace <YOUR_USERNAME> and <YOUR_PASSWORD> with your desired credentials. Always set them explicitly: if you omit them the container starts with the built-in default_user / Admin100, which are public and let anyone who can reach the published port authenticate as the admin user.
Readiness Note: docker ps reports the container as Up before DocumentDB can accept connections. Wait for the ready banner first: until docker logs documentdb-container 2>&1 | grep -q "=== DocumentDB is ready ==="; do sleep 2; done
Port Note: Port 10260 is used by default in these instructions to avoid conflicts with other local database services. You can use port 27017 (the standard MongoDB port) or any other available port if you prefer. If you do, be sure to update the port number in both your docker run command and your connection string accordingly.
Creating a new Node.js project
mkdir my-documentdb-app
cd my-documentdb-app
npm init -yInstalling the MongoDB driver
npm install mongodbDocumentDB Local accepts TLS connections on the gateway port and requires authentication. Connect with the username and password you set when starting the container, and because the container uses a self-signed certificate, the simplest local setup skips certificate validation with tlsAllowInvalidCertificates=true (in production, provide the gateway certificate instead).
const { MongoClient } = require('mongodb');
const uri = 'mongodb://<YOUR_USERNAME>:<YOUR_PASSWORD>@localhost:10260/?tls=true&tlsAllowInvalidCertificates=true';
const client = new MongoClient(uri);
async function connect() {
try {
await client.connect();
const db = client.db('your_database');
return db;
} catch (error) {
console.error('Connection error:', error);
throw error;
}
}Creating collections
const collection = db.collection('your_collection');Document operations