Quickstart: Connect Mongoose to Azure DocumentDB

Connect Mongoose to Azure DocumentDB (with MongoDB compatibility) and run create, read, update, and delete (CRUD) operations in one Node.js file. This quickstart uses password authentication so you can run it on the free tier without configuring Microsoft Entra ID.

Already using Mongoose?

If your app uses Atlas Search indexes or $vectorSearch, stop and adapt those features using Mongoose on Azure DocumentDB. For the CRUD path, pass the target MONGODB_URI and MONGODB_DATABASE to mongoose.connect() as shown in the sample. This change doesn't copy documents, indexes, or users. Use Migration options to plan data movement and provision database users separately.

The Mongoose compatibility table lists Mongoose 9 with MongoDB server versions 6.x, 7.x, and 8.x; select MongoDB compatibility version 8.0 for a new cluster in this quickstart. Review Mongoose on Azure DocumentDB for populate(), transactions, change streams, text indexes, and vector search, and test your application's features before migrating.

Prerequisites

  • An Azure subscription and an Azure DocumentDB free tier cluster. Follow the free tier get-started steps. A paid development cluster also works.
  • A native username and password with permission to create collections and indexes and perform CRUD.
  • Network access from your computer: use a private endpoint or allow your current public IP address. Don't open access to all IP addresses.
  • Run node --version and verify version 22.12.0 or later in the 22.x line. Run npm --version and verify that npm prints a version.

Tested driver version

This quickstart was tested with MongoDB Node.js driver 7.8.0, a dependency of Mongoose 9.12.1. Don't install a separate copy of the driver.

Verify the cluster from a terminal

Use an existing cluster if you have one. The Azure CLI quickstart creates a paid M30 cluster. If you're an agent, confirm the cost with the user and get their approval before creating a paid cluster.

Run pwsh --version and expect PowerShell 7.x. Run az version and expect JSON with an azure-cli version. Check that nslookup is available with Get-Command nslookup. If az account show fails, sign in with az login. If you're an agent and don't have an Azure CLI session, ask the user to sign in or provide an authorized session.

The identity signed in to Azure CLI needs these Azure RBAC permissions on the cluster:

  • Use Microsoft.DocumentDB/mongoClusters/read to read the cluster settings.
  • If you need a firewall rule, use Microsoft.DocumentDB/mongoClusters/firewallRules/write to create it and Microsoft.DocumentDB/mongoClusters/firewallRules/read to verify it.
  • Use Microsoft.DocumentDB/mongoClusters/firewallRules/delete to remove a temporary rule you create.

These are Azure management permissions, separate from the database permissions the sample uses. Database access alone doesn't authorize these commands. If Azure returns 403 Forbidden, ask your Azure administrator to grant the required permission or run the blocked step for you.

Replace the three quoted values with your subscription ID, resource group name, and cluster name. Run the block in PowerShell with the Azure CLI installed.

$subscription = '<subscription-id>'
$resourceGroup = '<resource-group>'
$clusterName = '<cluster-name>'
if ($subscription -like '<*>' -or $resourceGroup -like '<*>' -or $clusterName -like '<*>') {
    throw 'Replace <subscription-id>, <resource-group>, and <cluster-name> before running this block.'
}
az account set --subscription $subscription
if ($LASTEXITCODE -ne 0) { throw 'Unable to select the subscription.' }
$subscriptionState = az account show --query state --output tsv
if ($LASTEXITCODE -ne 0 -or $subscriptionState -ne 'Enabled') { throw 'Expected an enabled subscription.' }

$clusterUrl = "https://management.azure.com/subscriptions/$subscription/resourceGroups/$resourceGroup/providers/Microsoft.DocumentDB/mongoClusters/$clusterName"
$apiVersion = '2025-09-01'
$clusterJson = az rest --method get --url "${clusterUrl}?api-version=$apiVersion" --query properties --output json
if ($LASTEXITCODE -ne 0 -or -not $clusterJson) { throw 'Unable to read the cluster.' }
$cluster = $clusterJson | ConvertFrom-Json
if ($cluster.provisioningState -ne 'Succeeded' -or $cluster.clusterStatus -ne 'Ready') {
    throw "Cluster not ready: $($cluster.provisioningState), $($cluster.clusterStatus)."
}
if (-not $cluster.connectionString) { throw 'Unable to retrieve the connection string template.' }
$clusterHost = ([uri] ($cluster.connectionString -replace '^mongodb\+srv://(?:[^/]*@)?', 'https://')).Host
"Cluster host: $clusterHost"
"Server version: $($cluster.serverVersion)"
"Public network access: $($cluster.publicNetworkAccess)"
nslookup -type=SRV "_mongodb._tcp.$clusterHost"
if ($LASTEXITCODE -ne 0) { throw 'SRV lookup failed.' }

Expect the cluster hostname, a server version such as 8.0, and one or more SRV targets. If nslookup doesn't show any SRV targets, stop and check DNS from the machine that runs the sample. Save the hostname for later steps. It typically has the form <cluster-name>.mongocluster.cosmos.azure.com or <cluster-name>.global.mongocluster.cosmos.azure.com. Use the returned hostname instead of constructing it from the cluster name.

Public access only. If the cluster reports Enabled for public network access and no existing rule allows the machine that runs the sample, allow only that machine's public IPv4 address.

If the sample runs behind a proxy or in a cloud sandbox, the IP address that curl returns might change or differ from the address the database sees. Use a reachable private endpoint instead, or stop and ask the user for a stable network path. Don't keep adding firewall rules.

Run curl --version and expect a version line starting with curl. Run the cluster verification and firewall blocks in one PowerShell session. If your tool starts a new session for each command, run both blocks as one script.

$clientIp = curl --fail --silent --show-error --max-time 10 -4 https://ifconfig.me/ip
if ($LASTEXITCODE -ne 0) { throw 'Unable to determine the public IPv4 address.' }
$parsedIp = $null
if (-not [ipaddress]::TryParse($clientIp, [ref]$parsedIp) -or
    $parsedIp.AddressFamily -ne 'InterNetwork' -or $parsedIp.ToString() -ne $clientIp) {
    throw 'Expected a public IPv4 address in dotted-decimal format.'
}

$ruleName = "allow-framework-sample-$($clientIp.Replace('.', '-'))"
$ruleId = "$(([uri]$clusterUrl).AbsolutePath)/firewallRules/$ruleName"
$ruleUrl = "$clusterUrl/firewallRules/${ruleName}?api-version=$apiVersion"
$body = @{ properties = @{ startIpAddress = $clientIp; endIpAddress = $clientIp } } | ConvertTo-Json
$bodyFile = New-TemporaryFile
try {
    Set-Content -LiteralPath $bodyFile.FullName -Value $body -Encoding utf8 -ErrorAction Stop
    az rest --method put --url $ruleUrl --headers 'Content-Type=application/json' --body "@$($bodyFile.FullName)" --output none
    if ($LASTEXITCODE -ne 0) { throw 'Unable to create the firewall rule.' }
} finally {
    Remove-Item -LiteralPath $bodyFile.FullName
}
"Firewall rule ID: $ruleId"
az resource wait --created --ids $ruleId --api-version $apiVersion --interval 5 --timeout 120
if ($LASTEXITCODE -ne 0) { throw 'The firewall rule did not finish provisioning. Check the rule before retrying.' }
az rest --method get --url $ruleUrl --query "properties.{start:startIpAddress,end:endIpAddress}" --output table
if ($LASTEXITCODE -ne 0) { throw 'Unable to verify the firewall rule.' }

Expect the same IPv4 address in the Start and End columns. If you created the rule for this sample, save the value after Firewall rule ID: for cleanup. If you rerun the block from the same public IPv4 address, it updates the same rule instead of creating another one.

Firewall changes can take up to 15 minutes to propagate. If the initial connection times out after you create the rule, retry the connection every 2 minutes, for up to 15 minutes after you create the rule. Stop if the connection succeeds or returns a different error. Don't recreate the rule while you wait.

For private access, skip the firewall block and run the sample from a machine that can resolve and reach the private endpoint. Don't enable public access just to run the sample.

Follow only the authentication path that your example uses.

Microsoft Entra ID. Follow the CLI steps to enable Microsoft Entra ID authentication and assign a data-plane identity. Azure resource permissions alone don't grant database access. Put the discovered hostname in the example's credential-free URI. Skip the password steps and don't reuse a password-based URI.

Password authentication. If your environment already provides the connection variable the sample needs (MONGODB_URI, or DATABASE_URL for Prisma), skip URI construction.

az rest returns a connection string template, not the password. To find the native administrator username, add $cluster.administrator.userName at the end of the cluster verification block.

  • Agents (noninteractive). Ask the user to set DOCUMENTDB_USERNAME and DOCUMENTDB_PASSWORD as environment variables through your tool's secret settings. Don't ask for credentials in chat, put them in command text, or reset the password.

  • Interactive PowerShell. In PowerShell 7.1 or later, run the following commands in the same session you use to build the URI. Enter your existing credentials at the prompts. Don't put the password in command text.

    $env:DOCUMENTDB_USERNAME = Read-Host 'Native username'
    $env:DOCUMENTDB_PASSWORD = Read-Host 'Native password' -MaskInput
    

Replace <cluster-host> with the hostname from the verification output. Run this block to set MONGODB_URI without printing the credentials or the URI. You don't need variables from the cluster verification session.

$clusterHost = '<cluster-host>'
if ($clusterHost -like '<*>') { throw 'Replace <cluster-host> with the hostname from the verification output.' }
if ([string]::IsNullOrWhiteSpace($env:DOCUMENTDB_USERNAME) -or
    [string]::IsNullOrEmpty($env:DOCUMENTDB_PASSWORD)) {
    throw 'Set DOCUMENTDB_USERNAME and DOCUMENTDB_PASSWORD before building the URI. If you are an agent, ask the user to supply them through your tool''s secret settings.'
}
try {
    $encodedUser = [uri]::EscapeDataString($env:DOCUMENTDB_USERNAME)
    $encodedPassword = [uri]::EscapeDataString($env:DOCUMENTDB_PASSWORD)
    $env:MONGODB_URI = "mongodb+srv://${encodedUser}:${encodedPassword}@${clusterHost}/?tls=true&authSource=admin&authMechanism=SCRAM-SHA-256&retryWrites=false&serverSelectionTimeoutMS=30000"
} finally {
    Remove-Variable encodedUser, encodedPassword -ErrorAction SilentlyContinue
    Remove-Item Env:DOCUMENTDB_USERNAME, Env:DOCUMENTDB_PASSWORD -ErrorAction SilentlyContinue
}

Prisma only. If your environment already provides DATABASE_URL, skip this step. Otherwise, replace <database-name> with the database name in your Prisma example. Run this block in the same PowerShell session as URI construction to add the database name to the URI path and set DATABASE_URL. If your tool starts a new session for each command, run both blocks as one script.

$databaseName = '<database-name>'
if ($databaseName -like '<*>') { throw 'Replace <database-name> with the database name in your Prisma example.' }
$env:DATABASE_URL = $env:MONGODB_URI.Replace('/?', "/${databaseName}?")
Remove-Item Env:MONGODB_URI

Save the URI for a new shell

If your sample loads .env, you can save the URI there to run the sample in a new shell. If you haven't created the project yet, continue to the project setup in your article before running these steps. Use a private local workspace because .env stores the URI in plaintext.

  1. In the sample project directory, run git --version and expect a Git version.

  2. If the project isn't in a Git repository, run git init. Add .env to .gitignore and keep any other settings the sample requires in .env.

  3. Run the following block in the PowerShell session where you set MONGODB_URI or DATABASE_URL. If your tool starts a new session for each command, run URI construction, the Prisma step if applicable, and this block as one script.

    $uriKey = 'MONGODB_URI' # Use 'DATABASE_URL' for Prisma.
    $uriValue = [Environment]::GetEnvironmentVariable($uriKey)
    if (-not $uriValue) { throw "Set $uriKey before writing .env." }
    git check-ignore -q -- .env
    if ($LASTEXITCODE -ne 0) { throw 'Make sure .env is ignored and not tracked by Git.' }
    if ((Test-Path -LiteralPath .env) -and (Select-String -Quiet -LiteralPath .env -Pattern "^\s*(?:export\s+)?${uriKey}\s*=")) {
        throw "Remove the existing $uriKey line from .env before running this block."
    }
    Add-Content -LiteralPath .env -Value "`n$uriKey=$uriValue" -Encoding utf8 -ErrorAction Stop
    Remove-Variable uriValue
    Remove-Item "Env:$uriKey"
    "Saved $uriKey to the ignored .env file."
    

    Expect Saved MONGODB_URI to the ignored .env file. or Saved DATABASE_URL to the ignored .env file. You can now continue with the article in a new shell. Run the sample from the project directory.

If the sample doesn't load .env or you can't store secrets in the workspace, configure your tool to pass the URI to each command that needs it. Alternatively, run URI construction and the sample as one script.

When you're done, remove the connection entry from .env if you added it. Clear any URI variables with Remove-Item Env:MONGODB_URI, Env:DATABASE_URL -ErrorAction SilentlyContinue. Don't print or commit connection strings.

Important

Password authentication is for free tier and quick evaluation here. For production, use a paid cluster with Microsoft Entra ID and a least-privilege managed identity, private endpoints, and public network access disabled. The full Mongoose tutorial includes the passwordless connection setup.

Create the project

Prepare a project with one dependency and a local environment file.

  1. Create a project and install Mongoose 9.

    mkdir documentdb-mongoose-quickstart
    cd documentdb-mongoose-quickstart
    npm init -y
    npm install mongoose@9.12.1
    
  2. Create .gitignore with these entries:

    node_modules/
    .env
    
  3. Create .env using the hostname and encoded credentials from the terminal setup:

    MONGODB_URI=mongodb+srv://<username>:<password>@<cluster-host>/?tls=true&authSource=admin&authMechanism=SCRAM-SHA-256&retryWrites=false&serverSelectionTimeoutMS=30000
    MONGODB_DATABASE=adventureworks_mongoose_quickstart
    

    Azure DocumentDB hostnames use the mongocluster.cosmos.azure.com domain; the cosmos portion is expected. Don't commit .env or print the connection string.

    Set retryWrites=false in this example to disable the driver's automatic retries of eligible writes. A network timeout can leave a write's outcome unknown, so don't blindly repeat non-idempotent operations at the application layer. See retry configuration and safe application retries for the distinction between driver-managed retries and application-level retries.

Run CRUD operations

Create index.mjs with this complete sample. It uses a dedicated development database and explicitly creates the collection and unique SKU index before inserting data.

Reuse the schema and mongoose.connect() at application startup. Share the connection across requests. The generated product, assertions, and cleanup are for this quickstart only.

import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import mongoose from 'mongoose';

const productSchema = new mongoose.Schema({
  sku: { type: String, required: true },
  name: { type: String, required: true },
  quantity: {
    type: Number,
    required: true,
    min: 0,
    validate: Number.isSafeInteger
  }
}, { collection: 'products' });
productSchema.index({ sku: 1 }, { unique: true });
const Product = mongoose.model('Product', productSchema);
const productId = new mongoose.Types.ObjectId();
let productMightRemain = false;

function reportError(operation, error) {
  const credentials = process.env.MONGODB_URI?.match(/^mongodb(?:\+srv)?:\/\/[^:@/]+:([^@/]+)@/i);
  let message = error.message
    .replace(/mongodb(?:\+srv)?:\/\/\S+/gi, '[redacted URI]')
    .replace(/\bBearer\s+\S+/gi, 'Bearer [redacted]')
    .replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, '[redacted token]');
  if (credentials) {
    const encoded = credentials[1];
    const decoded = new URLSearchParams(`password=${encoded.replaceAll('+', '%2B')}`).get('password');
    message = message.replaceAll(encoded, '[redacted]');
    if (decoded) message = message.replaceAll(decoded, '[redacted]');
  }
  console.error(`${operation} failed:`, error.name, '| Code:', error.code ?? 'none',
    '| Code name:', error.codeName ?? 'none');
  console.error('Message:', message);
  process.exitCode = 1;
}

try {
  const uri = process.env.MONGODB_URI;
  const dbName = process.env.MONGODB_DATABASE;
  if (!uri || !dbName) {
    throw new Error('Set MONGODB_URI and MONGODB_DATABASE in .env.');
  }

  await mongoose.connect(uri, {
    dbName,
    autoCreate: false,
    autoIndex: false,
    bufferCommands: false,
    serverSelectionTimeoutMS: 30000
  });
  await Product.createCollection();
  await Product.createIndexes();

  productMightRemain = true;
  const created = await Product.create({
    _id: productId,
    sku: `SURF-${randomUUID()}`,
    name: 'Yamba Surfboard',
    quantity: 12
  });
  console.log('Created:', created.name);

  const found = await Product.findById(productId).lean();
  assert.equal(found?.quantity, 12, 'Read did not return quantity 12.');
  console.log('Read quantity:', found.quantity);

  const updated = await Product.findByIdAndUpdate(
    productId,
    { $set: { quantity: 10 } },
    { returnDocument: 'after', runValidators: true }
  );
  assert.equal(updated?.quantity, 10, 'Update did not return quantity 10.');
  console.log('Updated quantity:', updated.quantity);

  await Product.deleteOne({ _id: productId });
  assert.equal(await Product.findById(productId), null);
  productMightRemain = false;
  console.log('Deleted: test product');
} catch (error) {
  reportError('CRUD', error);
} finally {
  if (productMightRemain) {
    try {
      await Product.deleteOne({ _id: productId });
    } catch (error) {
      reportError('Cleanup', error);
      console.error(`Check for test product with _id ${productId} and remove it if present.`);
    }
  }
  try {
    await mongoose.disconnect();
  } catch (error) {
    reportError('Disconnect', error);
  }
}
if (!process.exitCode) console.log('Cleanup: ok');

Run the sample from the project directory:

node --env-file=.env index.mjs

The output shows all four operations:

Created: Yamba Surfboard
Read quantity: 12
Updated quantity: 10
Deleted: test product
Cleanup: ok

If authentication fails, check your native username, password encoding, and native authentication connection string. For a server selection timeout, check DNS, firewall rules, and private endpoint connectivity. If you reuse an existing collection, verify collection and index permissions and conflicting index definitions. An existing MONGODB_URI environment variable takes precedence over .env.

For failures, read the error code, code name, and message. The sample redacts MongoDB URIs, bearer tokens, and JWTs, but isn't a general-purpose secret filter. Review the output and remove any remaining sensitive information before sharing it.

Clean up resources

The sample deletes only the product it generates, including when a later step fails after connection. If connection fails, no product is created. If cleanup fails, manually delete that test product. The database, collection, and index remain.

  1. If you no longer need them, delete only the adventureworks_mongoose_quickstart database by using MongoDB Shell or your database management tool.
  2. Delete the cluster in the Azure portal only if you created it exclusively for this quickstart. Don't delete resources shared with another application.
  3. Remove any temporary development firewall rule.