Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Use Mongoose with Azure DocumentDB (with MongoDB compatibility) to build an API for a retailer that manages a product catalog and reserves inventory. Use Mongoose to model documents and Express to expose HTTP endpoints. Choose password authentication for the free tier and quick evaluation, or Microsoft Entra ID for passwordless database access on a paid cluster.
For a smaller first example, start with Quickstart: Connect Mongoose to Azure DocumentDB.
You learn how to:
- Define a product schema with validation and indexes.
- Connect Mongoose with Microsoft Entra ID or password authentication.
- Create, query, update, and delete products.
- Reserve inventory without allowing the quantity to become negative.
- Test successful requests and common error cases.
Prerequisites
- An existing Azure DocumentDB cluster. For evaluation, use the free tier. Free tier doesn't support Microsoft Entra ID; use the password option in this tutorial.
- For password authentication, a native username and password with permission to create collections and indexes and perform CRUD.
- For Microsoft Entra ID, a paid cluster with Microsoft Entra authentication configured, with your development identity authorized to create collections and indexes and read and write documents in the tutorial database. Azure subscription permissions alone don't grant database access.
- Network access from your development computer to the cluster. Use a private endpoint, or allow your development computer's public IP address.
- Run
node --versionand verify version 22.12.0 or later in the 22.x line. Runnpm --versionand verify that npm prints a version. - For Microsoft Entra ID only, Azure CLI, signed in with the identity authorized for the cluster. If you haven't signed in, follow Sign in interactively with Azure CLI.
This example uses Mongoose 9, Express 5, and Azure Identity 4. Mongoose uses the MongoDB Node.js driver internally; you don't need to install a separate copy of the driver.
Tested driver version
This tutorial was tested with MongoDB Node.js driver 7.8.0, a dependency of Mongoose 9.12.1, using Microsoft Entra ID authentication.
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/readto read the cluster settings. - If you need a firewall rule, use
Microsoft.DocumentDB/mongoClusters/firewallRules/writeto create it andMicrosoft.DocumentDB/mongoClusters/firewallRules/readto verify it. - Use
Microsoft.DocumentDB/mongoClusters/firewallRules/deleteto 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_USERNAMEandDOCUMENTDB_PASSWORDas 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.
In the sample project directory, run
git --versionand expect a Git version.If the project isn't in a Git repository, run
git init. Add.envto.gitignoreand keep any other settings the sample requires in.env.Run the following block in the PowerShell session where you set
MONGODB_URIorDATABASE_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.orSaved 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.
For paid evaluation clusters, M10, M20, M25, and M30 offer near-instant provisioning. Follow the portal creation steps and choose a tier appropriate for your workload.
Important
This API is a local development sample. It listens only on 127.0.0.1 and doesn't authenticate HTTP callers. Before exposing it to other users, add API authentication and authorization, HTTPS, and request rate limits. For production database access, use private endpoints, disable public network access, and authorize a managed identity with only the required database permissions.
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. Provision database users separately.
This example pins Mongoose 9.12.1 and uses its bundled MongoDB Node.js driver. The Mongoose version compatibility table lists Mongoose 9 with MongoDB server versions 6.x, 7.x, and 8.x. Azure DocumentDB documents MongoDB compatibility versions 5.0 through 8.0; use 8.0 for a new cluster following this tutorial.
Before cutover, assess compatibility and choose a migration tool, migrate your data and indexes, and run your application's integration tests against the target. For Atlas-specific steps, see Migrate from MongoDB Atlas. Search indexes and queries can require changes even when CRUD code stays the same.
Why keep retryWrites=false?
Set retryWrites=false in this example to disable the MongoDB driver's automatic retries of eligible writes. This option doesn't disable connection pooling or all read retries.
Driver-managed retryable writes and application-level retries are different mechanisms. When retryable writes are supported and enabled, the driver uses protocol-level identifiers so the server can recognize a retry and avoid applying the same eligible write twice. Independently repeating an application operation doesn't provide that protection.
A network timeout can leave a write's outcome unknown: blindly repeating this tutorial's $inc reservation can decrement inventory twice. The stock filter prevents negative inventory, not duplicate reservations. Before adding application-level retries, implement a persisted reservation identifier and deduplication that remain safe under concurrent requests. Use bounded retries with backoff only when replay is safe.
Mongoose on Azure DocumentDB
These notes map Mongoose APIs to documented service capabilities. They don't certify every plugin or workload. Review MongoDB feature compatibility and query language compatibility, and test the features your application uses on its target tier.
| Mongoose feature | Behavior and considerations |
|---|---|
populate() |
Mongoose resolves references with separate queries, not an automatic $lookup translation. Index fields used to find referenced documents and account for additional round trips. See Mongoose population. |
| Sessions and transactions | Use Mongoose sessions and pass the session to each operation. Azure DocumentDB supports multi-operation transactions, with a 30-second maximum transaction lifetime. This tutorial needs only a single-document atomic update. |
Model.watch() |
Uses change streams. For multishard clusters, turn off Rebalancer and enable the preview feature under Settings > Features > Change streams for multishard clusters. You don't need this feature for the inventory API in this tutorial. |
| Text indexes | Declare a text index in the schema and create it explicitly. Use $text queries and review text index limits, including one text index per collection. Atlas Search indexes aren't interchangeable with these indexes. |
Model.aggregate() |
Sends an aggregation pipeline to the service. Check each stage and operator against the compatibility reference. Mongoose doesn't cast aggregation pipeline values; construct ObjectId values explicitly when needed. |
Vector search through aggregate() |
Create an Azure DocumentDB vector index, then use the $search stage with cosmosSearch in the pipeline. Don't copy Atlas $vectorSearch syntax unchanged. Follow vector search for index options and query syntax; free tier doesn't support HNSW or DiskANN indexes. |
Understand the scenario
Each product has a unique SKU, a name, a category, a price in integer cents, and an available quantity. Store prices in integer cents to avoid floating-point arithmetic for this example's single currency.
The API uses the adventureworks_mongoose database and the products collection. Use a separate development database rather than an existing production database.
| Method | Endpoint | Purpose |
|---|---|---|
POST |
/products |
Create a product. |
GET |
/products?category=gear&page=1 |
List a category's products in pages of 20. |
PATCH |
/products/:id |
Update a product's name, category, or price. |
POST |
/products/:id/reserve |
Decrease available inventory if enough stock remains. |
DELETE |
/products/:id |
Delete a product. |
The reservation operation updates one document. It doesn't create an order or coordinate inventory across multiple products.
Create the project
Create an empty project and install the dependencies.
Create a project directory and initialize a Node.js project.
mkdir documentdb-mongoose-inventory cd documentdb-mongoose-inventory npm init -yInstall the dependencies.
npm install mongoose@9.12.1 express@5 @azure/identity@4Keep the generated
package-lock.jsonwith your application to preserve the resolved dependency versions. The.mjsextension in the following files enables ECMAScript modules without changingpackage.json.For password-only use, omit
@azure/identity@4from the install command. The connection code loads Azure Identity only in Entra mode.Create a
.gitignorefile with the following content:node_modules/ .envCreate a
.envfile. Replace<cluster-host>with the hostname from Verify the cluster from a terminal.MONGODB_AUTH=entra MONGODB_URI=mongodb+srv://<cluster-host>/?tls=true&retryWrites=false MONGODB_DATABASE=adventureworks_mongooseFor example, the hostname can have the form
<cluster-name>.global.mongocluster.cosmos.azure.com. Don't add a username or password to this URI. The next section configures Microsoft Entra authentication in code.If you copy a password-based connection string from the portal, don't use it unchanged. Keep only the hostname in the template above. Remove the
username:password@portion and anyauthMechanism=SCRAM-SHA-256orauthMechanismPropertiesparameters. The application supplies its OIDC authentication options in code; combining them with a password causes aMongoInvalidArgumentErrorbefore the driver connects.For the free tier and quick evaluation, use this alternative
.envinstead. Use the hostname and encoded credentials from the terminal setup. This template enables TLS and setsretryWrites=false. See retry configuration considerations for the distinction between driver-managed retries and application-level retries.MONGODB_AUTH=password MONGODB_URI=mongodb+srv://<username>:<password>@<cluster-host>/?tls=true&authSource=admin&authMechanism=SCRAM-SHA-256&retryWrites=false&serverSelectionTimeoutMS=30000 MONGODB_DATABASE=adventureworks_mongoosePercent-encode reserved characters in the username and password with
encodeURIComponentbefore placing them in the URI. Don't encode the entire URI or commit.env. This option doesn't require Azure CLI sign-in or Microsoft Entra configuration.Azure DocumentDB hostnames use the
mongocluster.cosmos.azure.comdomain. Thecosmosportion is expected and doesn't mean you're connecting to an Azure Cosmos DB for MongoDB RU-based account.
Connect Mongoose to Azure DocumentDB
Create database.mjs with the following content:
import mongoose from 'mongoose';
export async function connectDatabase() {
const uri = process.env.MONGODB_URI;
const dbName = process.env.MONGODB_DATABASE;
const authMode = process.env.MONGODB_AUTH;
if (!uri || !dbName) {
throw new Error('Set MONGODB_URI and MONGODB_DATABASE in .env.');
}
if (!['entra', 'password'].includes(authMode)) {
throw new Error('Set MONGODB_AUTH to entra or password in .env.');
}
const options = {
dbName,
autoCreate: false,
autoIndex: false,
bufferCommands: false,
maxPoolSize: 10,
serverSelectionTimeoutMS: 30000
};
if (authMode === 'entra') {
const { DefaultAzureCredential } = await import('@azure/identity');
const credential = new DefaultAzureCredential();
options.authSource = '$external';
options.authMechanism = 'MONGODB-OIDC';
options.authMechanismProperties = {
ALLOWED_HOSTS: ['*.mongocluster.cosmos.azure.com'],
OIDC_CALLBACK: async (params) => {
const token = await credential.getToken(
'https://ossrdbms-aad.database.windows.net/.default',
{ abortSignal: params.timeoutContext }
);
if (!token) {
throw new Error('Microsoft Entra ID did not return an access token.');
}
return {
accessToken: token.token,
expiresInSeconds: Math.floor(
(token.expiresOnTimestamp - Date.now()) / 1000
)
};
}
};
}
await mongoose.connect(uri, options);
}
Mongoose passes the authentication options to its MongoDB driver. In password mode, the driver uses the SCRAM credentials in the URI and no OIDC options. In Entra mode, the driver invokes the OIDC callback when it needs an access token, including when a token expires. DefaultAzureCredential can use your Azure CLI sign-in locally and a managed identity when you host the application in Azure. The identity used in either environment must also have database permissions.
The token scope https://ossrdbms-aad.database.windows.net/.default is the resource used in the Microsoft Entra connection examples. In the driver bundled with the Mongoose version listed earlier, OIDCCallbackParams.timeoutContext is an AbortSignal; pass it to Azure Identity's abortSignal option so token acquisition observes the callback's cancellation signal.
ALLOWED_HOSTS explicitly permits Azure DocumentDB hosts for OIDC authentication. The driver's default allow list doesn't include this domain. The driver checks the actual hosts returned by DNS SRV resolution, which can differ from the cluster hostname in your URI. Keep this list restricted to the service domain; don't use * to allow arbitrary hosts.
The application reuses one connection pool rather than opening a connection for each request. It disables automatic index creation so that the startup step can explicitly create and await the indexes before accepting requests.
Define the product model
Create product.mjs with the following content:
import mongoose from 'mongoose';
const productSchema = new mongoose.Schema({
sku: { type: String, required: true, trim: true, maxlength: 64 },
name: { type: String, required: true, trim: true, maxlength: 200 },
category: { type: String, required: true, trim: true, maxlength: 100 },
priceCents: {
type: Number,
required: true,
min: 0,
validate: Number.isSafeInteger
},
quantity: {
type: Number,
required: true,
min: 0,
validate: Number.isSafeInteger
}
}, {
collection: 'products',
timestamps: true,
strict: 'throw'
});
productSchema.index({ sku: 1 }, { unique: true });
productSchema.index({ category: 1, name: 1, _id: 1 });
export const Product = mongoose.model('Product', productSchema);
The unique SKU index prevents duplicate products. The compound index supports filtering by category and sorting by name, with _id as a tie-breaker. Azure DocumentDB automatically indexes _id, but you must explicitly create other indexes.
Mongoose validation runs in your application, not as a database-wide rule. Other clients can bypass it. Also, a unique index violation is a database error, not a Mongoose validation error.
Implement the API
The API validates JSON request bodies and product IDs before processing requests. The product routes create, list, update, and delete products. A separate reservation route conditionally decreases stock, and a shared error handler maps validation failures and duplicate SKUs to HTTP responses.
Create app.mjs with the following content:
import express from 'express';
import mongoose from 'mongoose';
import { Product } from './product.mjs';
export const app = express();
app.disable('x-powered-by');
app.use(express.json({ limit: '16kb' }));
app.use((req, res, next) => {
if (['POST', 'PATCH'].includes(req.method) &&
(!req.body || typeof req.body !== 'object' || Array.isArray(req.body))) {
return res.status(400).json({ error: 'Provide a JSON object.' });
}
next();
});
app.param('id', (req, res, next, id) => {
if (!mongoose.isObjectIdOrHexString(id)) {
return res.status(400).json({ error: 'Invalid product ID.' });
}
next();
});
app.post('/products', async (req, res) => {
const { sku, name, category, priceCents, quantity } = req.body;
const product = await Product.create({
sku, name, category, priceCents, quantity
});
res.status(201).json(product);
});
app.get('/products', async (req, res) => {
const { category } = req.query;
const pageText = req.query.page ?? '1';
const page = Number(pageText);
if (typeof category !== 'string' || !category.trim() ||
category.trim().length > 100 ||
typeof pageText !== 'string' || !/^\d+$/.test(pageText) ||
!Number.isSafeInteger(page) || page < 1 || page > 1000) {
return res.status(400).json({
error: 'Provide a category and a page number from 1 to 1000.'
});
}
const products = await Product.find({ category: category.trim() })
.sort({ name: 1, _id: 1 })
.skip((page - 1) * 20)
.limit(20)
.lean();
res.json({ page, products });
});
app.patch('/products/:id', async (req, res) => {
const updates = Object.fromEntries(
Object.entries(req.body).filter(([field]) =>
['name', 'category', 'priceCents'].includes(field))
);
if (Object.keys(updates).length === 0) {
return res.status(400).json({
error: 'Provide name, category, or priceCents to update.'
});
}
const product = await Product.findByIdAndUpdate(
req.params.id,
{ $set: updates },
{ returnDocument: 'after', runValidators: true }
);
if (!product) {
return res.status(404).json({ error: 'Product not found.' });
}
res.json(product);
});
app.post('/products/:id/reserve', async (req, res) => {
const { quantity } = req.body;
if (!Number.isSafeInteger(quantity) || quantity <= 0) {
return res.status(400).json({ error: 'Quantity must be a positive integer.' });
}
const product = await Product.findOneAndUpdate(
{ _id: req.params.id, quantity: { $gte: quantity } },
{ $inc: { quantity: -quantity } },
{ returnDocument: 'after' }
);
if (!product) {
return res.status(409).json({
error: 'Product not found or insufficient inventory.'
});
}
res.json(product);
});
app.delete('/products/:id', async (req, res) => {
const product = await Product.findByIdAndDelete(req.params.id);
if (!product) {
return res.status(404).json({ error: 'Product not found.' });
}
res.status(204).end();
});
app.use((error, req, res, next) => {
if (res.headersSent) {
return next(error);
}
if (error.code === 11000) {
return res.status(409).json({ error: 'A product with this SKU already exists.' });
}
if (['ValidationError', 'CastError', 'StrictModeError'].includes(error.name)) {
return res.status(400).json({ error: 'Invalid product fields.' });
}
if (error.type === 'entity.parse.failed') {
return res.status(400).json({ error: 'Invalid JSON.' });
}
if (error.type === 'entity.too.large') {
return res.status(413).json({ error: 'Request body is too large.' });
}
console.error('Request failed:', error.name);
res.status(500).json({ error: 'The request could not be completed.' });
});
Express 5 forwards rejected promises from asynchronous route handlers to the error handler. The API constructs filters and updates from explicitly allowed fields instead of passing request objects directly to Mongoose.
The inventory filter and $inc execute as one atomic update. If another request consumes the remaining stock first, the condition no longer matches. The API returns 409 rather than making inventory negative. Mongoose update validators don't validate $inc, so the positive-integer check and the database filter enforce this operation's quantity constraint.
Page-based pagination keeps this example small. For a large catalog or frequent concurrent catalog changes, use cursor-based pagination rather than increasingly large skip values.
Start the application
Reuse database.mjs and share the Mongoose connection across requests. The inventory routes and HTTP test data are examples, not application infrastructure.
Create server.mjs with the following content:
import mongoose from 'mongoose';
import { connectDatabase } from './database.mjs';
import { Product } from './product.mjs';
import { app } from './app.mjs';
let stage = 'connect to the database';
try {
console.log('[startup] Connecting to the database...');
await connectDatabase();
console.log('[startup] Database connected.');
stage = 'create the products collection';
console.log('[startup] Creating the products collection...');
await Product.createCollection();
stage = 'create the product indexes';
console.log('[startup] Creating the product indexes...');
await Product.createIndexes();
const server = app.listen(3000, '127.0.0.1', () => {
console.log('[http] Inventory API: http://127.0.0.1:3000');
});
let stopping = false;
const shutdown = () => {
if (stopping) return;
stopping = true;
server.close(() => void disconnect());
};
process.once('SIGINT', shutdown);
process.once('SIGTERM', shutdown);
server.once('error', (error) => {
process.exitCode = 1;
console.error('[http] Server failed:', error.code, error.message);
shutdown();
});
} catch (error) {
const message = error.message
.replace(/mongodb(?:\+srv)?:\/\/[^\s]+/gi, '[redacted MongoDB 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]');
console.error(`[startup] Failed to ${stage}.`);
console.error('Error:', error.name, '| Code:', error.code ?? 'none',
'| Code name:', error.codeName ?? 'none');
console.error('Message:', message);
process.exitCode = 1;
await disconnect();
}
async function disconnect() {
try {
await mongoose.disconnect();
} catch (error) {
process.exitCode = 1;
console.error('[shutdown] Database disconnect failed:', error.name);
}
}
Run the application
After you create server.mjs, start the application from the project directory:
node --env-file=.env server.mjs
When the connection and index creation succeed, the terminal displays:
[startup] Connecting to the database...
[startup] Database connected.
[startup] Creating the products collection...
[startup] Creating the product indexes...
[http] Inventory API: http://127.0.0.1:3000
Creating indexes at startup is convenient for this small development database. In production, manage index creation as a separate deployment step rather than rebuilding or checking indexes on every application startup. createIndexes() doesn't remove indexes that aren't declared in your Mongoose schema.
Test the API
Keep the API running and open a second terminal with curl installed. These requests don't require another programming language. On Windows PowerShell, use curl.exe instead of curl to avoid its Invoke-WebRequest alias. Each command prints response headers, including the HTTP status, followed by the JSON body.
Create
product.jsonin the test terminal's working directory. Use a unique SKU for each test run, and keep it unchanged for the duplicate request.{ "sku": "SURF-CURL-001", "name": "Yamba Surfboard", "category": "gear-surf-surfboards", "priceCents": 85000, "quantity": 12 }Create the product. Expect
201, quantity12, and an_idstring. Record this ID and replace<product-id>in the following commands with it.curl --include --request POST "http://127.0.0.1:3000/products" --header "Content-Type: application/json" --data-binary "@product.json"Run the same command again. Expect
409because the SKU already exists.List products in the category. Expect
200and aproductsarray. The list returns 20 products per page; your product might be on a later page if the category already contains data.curl --include "http://127.0.0.1:3000/products?category=gear-surf-surfboards&page=1"Create
price.json:{ "priceCents": 82000 }Update the price. Expect
200andpriceCentsequal to82000.curl --include --request PATCH "http://127.0.0.1:3000/products/<product-id>" --header "Content-Type: application/json" --data-binary "@price.json"Create
reservation.json:{ "quantity": 2 }Reserve two units. Expect
200and quantity10.curl --include --request POST "http://127.0.0.1:3000/products/<product-id>/reserve" --header "Content-Type: application/json" --data-binary "@reservation.json"Change the quantity in
reservation.jsonto11and repeat the reservation command. Expect409because only 10 units remain. Then change it to-1and repeat. Expect400.Change
priceCentsinprice.jsonto-1and repeat the price update command. Expect400.Try an invalid ID. Expect
400.curl --include --request DELETE "http://127.0.0.1:3000/products/not-an-objectid"Delete only the product created in this test, even if an earlier check failed. Expect
204with no body. Repeat the command and expect404.curl --include --request DELETE "http://127.0.0.1:3000/products/<product-id>"List the category again. Expect
200and verify that the deleted_idis no longer present.curl --include "http://127.0.0.1:3000/products?category=gear-surf-surfboards&page=1"
Remove the three local JSON files when you finish. If you use another API port, replace 3000 in the commands.
Troubleshoot common issues
| Symptom | Action |
|---|---|
Startup fails with MongoServerError. |
Read the failed operation in the [startup] line, followed by the error code, code name, and message. For Entra mode, verify the cluster authentication method and identity's database role assignment. For password mode, check the native authentication credentials. If collection or index creation fails, check the permissions for that operation and any existing collection or index definitions. |
Startup fails with Host ... is not valid for OIDC authentication with ALLOWED_HOSTS. |
Set ALLOWED_HOSTS: ['*.mongocluster.cosmos.azure.com'] in authMechanismProperties, as shown in database.mjs. The allow list must cover the service hosts returned by DNS SRV resolution, not just the cluster hostname in the URI. |
Startup fails with another MongoInvalidArgumentError. |
Read the Message: line printed by server.mjs to identify the rejected option. Don't assume every error of this type is password-related. Also check for an existing MONGODB_URI environment variable: Node.js doesn't override it with the value from --env-file. |
Startup fails with MongoInvalidArgumentError and a message that no password is allowed. |
With MONGODB_AUTH=entra, remove the username, password, and SCRAM parameters from the URI. For password authentication, set MONGODB_AUTH=password instead; don't combine SCRAM credentials with OIDC options. |
| Startup fails with an authentication error. | In Entra mode, verify your Azure CLI identity, tenant, cluster authentication configuration, and database role assignment. In password mode, verify the portal username and password, percent-encoding, and SCRAM connection string. Free tier requires password mode. |
| Startup fails with a server selection timeout. | Verify the hostname, DNS resolution, firewall rules, and private endpoint connectivity from your computer. |
| Startup fails while creating collections or indexes. | Verify that your database identity has the required permissions. If you reuse an existing collection, check for duplicate SKUs or conflicting index definitions. |
The API returns 409 when creating a product. |
Use a different SKU. The unique index rejects duplicates. |
The API returns 409 when reserving inventory. |
Verify the product ID and available stock. The API intentionally uses the same response for a missing product and insufficient inventory. |
Startup fails with EADDRINUSE. |
Stop the other process using port 3000, or change the port in app.listen() in server.mjs and replace 3000 in the curl test commands with that port. |
The startup diagnostic is for local troubleshooting. It 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. Don't return database error details, connection strings, or tokens in HTTP responses or shared logs.
Clean up resources
The test deletes its product but leaves the tutorial database, collection, and indexes in place.
- Stop the server with Ctrl+C.
- If you no longer need the tutorial data, delete only the
adventureworks_mongoosedatabase by using MongoDB Shell or your database management tool. - If you created an Azure DocumentDB cluster exclusively for this tutorial, delete that cluster in the Azure portal to stop its charges. Don't delete a cluster or resource group used by other applications.
- Remove any temporary development firewall rule you added.