This repository shows how to use Cosmos DB with Node.js and the MongoDB protocol with the popular mongoose npm package.
- create a Cosmos DB account and database using Azure CLI
- code examples with mongoose library
- cost-optimized examples with mongoose discriminators
Example Demo Output:
$ npm run simple-examples
> node examples/simple/run.js
[INFO] Connected (…)
[INFO] Number of Families: 4
[INFO] New Family saved (…)
[INFO] Number of Families: 5
[INFO] Disconnected, bye bye
By default Mongoose creates a new colleciton per model. Because Azure charges you per collection, it makes sense to use mongoose discriminators to leverage schema inheritance to optimize costs:
Then you only pay once for the Base
model collection instaead of doubling costs for Family
and Vacation
models.
For more details see the cost optimized examples →
N.B. Cosmos DB account names must be globally unique
export COSMOS_DEMO_ACCOUNT_NAME=mycosmosdb-demo
export COSMOS_DEMO_RG_NAME=mycosmosdb-demo-rg
- Free Tier: is limited to 1 account per subscription. Remove
--enable-free-tier
if required - Enable Aggregation Pipeline for mongoose's rich API, so we can use e.g.
db.collection.countDocuments()
az cosmosdb create \
--name $COSMOS_DEMO_ACCOUNT_NAME \
--resource-group $COSMOS_DEMO_RG_NAME \
--kind MongoDB \
--capabilities EnableAggregationPipeline \
--enable-free-tier true
We will name ours mongodemo
az cosmosdb mongodb database create \
--resource-group $COSMOS_DEMO_RG_NAME \
--account-name $COSMOS_DEMO_ACCOUNT_NAME \
--name mongodemo
Note: jq is used to parse JSON output from Azure CLI and is pre-installed on Azure DevOps hosted ubuntu agents.
az cosmosdb keys list \
--name $COSMOS_DEMO_ACCOUNT_NAME \
--resource-group $COSMOS_DEMO_RG_NAME \
| jq '.primaryMasterKey' | sed 's/"//g'
First you need the code in this repository
git clone https://github.com/julie-ng/cosmosdb-mongoose-example
To test your connection locally, copy .env.example
and rename it to .env
filling in your configuration, for example
# .env
DB_HOST=mycosmosdb.documents.azure.com
DB_USER=mycosmosdb
DB_PASSWORD=myaccountprimarykey
DB_NAME=mydbname
DB_PORT=10255
npm install
npm run simple-examples
npm run optimized-examples
Don't worry. These examples are easy to follow. But just in case, you need some guidance:
-
Promises and Async/Await
To run multiple examples with a single connection, we have to add some extra Promises. See details at./examples/README.md
→ -
ES6 Modules
Compared to the official Microsoft documentation, each operation is split into its own file, e.g.family.add.js
.
Have fun exploring the examples. If you have any questions, open an issue →