Quickstart - Azure Cosmos DB for NoSQL client library for Node.js
APPLIES TO:
NoSQL
Get started with the Azure Cosmos DB client library for JavaScript to create databases, containers, and items within your account. Follow these steps to install the package and try out example code for basic tasks.
Note
The example code snippets are available on GitHub as a Node.js project.
Prerequisites
- An Azure account with an active subscription.
- No Azure subscription? You can try Azure Cosmos DB free with no credit card required.
- Node.js LTS
- Azure Command-Line Interface (CLI) or Azure PowerShell
Prerequisite check
- In a terminal or command window, run
node --version
to check that the Node.js version is one of the current long term support (LTS) versions. - Run
az --version
(Azure CLI) orGet-Module -ListAvailable AzureRM
(Azure PowerShell) to check that you have the appropriate Azure command-line tools installed.
Setting up
This section walks you through creating an Azure Cosmos account and setting up a project that uses Azure Cosmos DB SQL API client library for JavaScript to manage resources.
Create an Azure Cosmos DB account
Tip
No Azure subscription? You can try Azure Cosmos DB free with no credit card required. If you create an account using the free trial, you can safely skip ahead to the Create a new JavaScript project section.
This quickstart will create a single Azure Cosmos DB account using the API for NoSQL.
Tip
For this quickstart, we recommend using the resource group name msdocs-cosmos-quickstart-rg
.
Sign in to the Azure portal.
From the Azure portal menu or the Home page, select Create a resource.
On the New page, search for and select Azure Cosmos DB.
On the Select API option page, select the Create option within the NoSQL section. Azure Cosmos DB has six APIs: NoSQL, MongoDB, PostgreSQL, Apache Cassandra, Apache Gremlin, and Table. Learn more about the API for NoSQL.
On the Create Azure Cosmos DB Account page, enter the following information:
Setting Value Description Subscription Subscription name Select the Azure subscription that you wish to use for this Azure Cosmos account. Resource Group Resource group name Select a resource group, or select Create new, then enter a unique name for the new resource group. Account Name A unique name Enter a name to identify your Azure Cosmos account. The name will be used as part of a fully qualified domain name (FQDN) with a suffix of documents.azure.com, so the name must be globally unique. The name can only contain lowercase letters, numbers, and the hyphen (-) character. The name must also be between 3-44 characters in length. Location The region closest to your users Select a geographic location to host your Azure Cosmos DB account. Use the location that is closest to your users to give them the fastest access to the data. Capacity mode Provisioned throughput or Serverless Select Provisioned throughput to create an account in provisioned throughput mode. Select Serverless to create an account in serverless mode. Apply Azure Cosmos DB free tier discount Apply or Do not apply Enable Azure Cosmos DB free tier. With Azure Cosmos DB free tier, you'll get the first 1000 RU/s and 25 GB of storage for free in an account. Learn more about free tier. Note
You can have up to one free tier Azure Cosmos DB account per Azure subscription and must opt-in when creating the account. If you do not see the option to apply the free tier discount, this means another account in the subscription has already been enabled with free tier.
Select Review + create.
Review the settings you provide, and then select Create. It takes a few minutes to create the account. Wait for the portal page to display Your deployment is complete before moving on.
Select Go to resource to go to the Azure Cosmos DB account page.
From the API for NoSQL account page, select the Keys navigation menu option.
Record the values from the URI and PRIMARY KEY fields. You'll use these values in a later step.
Create a new JavaScript project
Create a new Node.js application in an empty folder using your preferred terminal.
npm init -y
Edit the
package.json
file to use ES6 modules by adding the"type": "module",
entry. This setting allows your code to use modern async/await syntax.{ "name": "azure-cosmos-db-sql-api-quickstart", "version": "1.0.0", "description": "Azure Cosmos DB for Core (SQL) quickstart with JavaScript", "main": "index", "type": "module", "scripts": { "start": "node index.js", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "cosmos", "quickstart" ], "author": "diberry", "license": "MIT", "dependencies": { "@azure/cosmos": "^3.17.0", "dotenv": "^16.0.2" } }
Install packages
Add the @azure/cosmos and @azure/identity npm packages to the Node.js project.
npm install @azure/cosmos npm install @azure/identity
Add the dotenv npm package to read environment variables from a
.env
file.npm install dotenv
Configure environment variables
To use the URI and PRIMARY KEY values within your code, persist them to new environment variables on the local machine running the application. To set the environment variable, use your preferred terminal to run the following commands:
$env:COSMOS_ENDPOINT = "<cosmos-account-URI>"
$env:COSMOS_KEY = "<cosmos-account-PRIMARY-KEY>"
Object model
Before you start building the application, let's look into the hierarchy of resources in Azure Cosmos DB. Azure Cosmos DB has a specific object model used to create and access resources. The Azure Cosmos DB creates resources in a hierarchy that consists of accounts, databases, containers, and items.
Hierarchical diagram showing an Azure Cosmos DB account at the top. The account has two child database nodes. One of the database nodes includes two child container nodes. The other database node includes a single child container node. That single container node has three child item nodes.
For more information about the hierarchy of different resources, see working with databases, containers, and items in Azure Cosmos DB.
You'll use the following JavaScript classes to interact with these resources:
CosmosClient
- This class provides a client-side logical representation for the Azure Cosmos DB service. The client object is used to configure and execute requests against the service.Database
- This class is a reference to a database that may, or may not, exist in the service yet. The database is validated server-side when you attempt to access it or perform an operation against it.Container
- This class is a reference to a container that also may not exist in the service yet. The container is validated server-side when you attempt to work with it.SqlQuerySpec
- This interface represents a SQL query and any query parameters.QueryIterator<>
- This class represents an iterator that can track the current page of results and get a new page of results.FeedResponse<>
- This class represents a single page of responses from the iterator.
Code examples
The sample code described in this article creates a database named cosmicworks
with a container named products
. The products
table is designed to contain product details such as name, category, quantity, and a sale indicator. Each product also contains a unique identifier.
For this sample code, the container will use the category as a logical partition key.
Authenticate the client
Application requests to most Azure services must be authorized. Using the DefaultAzureCredential
class provided by the Azure Identity client library is the recommended approach for implementing passwordless connections to Azure services in your code.
You can also authorize requests to Azure services using passwords, connection strings, or other credentials directly. However, this approach should be used with caution. Developers must be diligent to never expose these secrets in an unsecure location. Anyone who gains access to the password or secret key is able to authenticate. DefaultAzureCredential
offers improved management and security benefits over the account key to allow passwordless authentication. Both options are demonstrated in the following example.
DefaultAzureCredential
is a class provided by the Azure Identity client library for .NET. To learn more about DefaultAzureCredential
, see the DefaultAzureCredential overview. DefaultAzureCredential
supports multiple authentication methods and determines which method should be used at runtime. This approach enables your app to use different authentication methods in different environments (local vs. production) without implementing environment-specific code.
For example, your app can authenticate using your Visual Studio sign-in credentials when developing locally, and then use a managed identity once it has been deployed to Azure. No code changes are required for this transition.
When developing locally with passwordless authentication, make sure the user account that connects to Cosmos DB is assigned a role with the correct permissions to perform data operations. Currently, Azure Cosmos DB for NoSQL doesn't include built-in roles for data operations, but you can create your own using the Azure CLI or PowerShell.
Roles consist of a collection of permissions or actions that a user is allowed to perform, such as read, write, and delete. You can read more about configuring role-based access control (RBAC) in the Cosmos DB security configuration documentation.
Create the custom role
Create a role using the
az role definition create
command. Pass in the Cosmos DB account name and resource group, followed by a body of JSON that defines the custom role. The following example creates a role namedPasswordlessReadWrite
with permissions to read and write items in Cosmos DB containers. The role is also scoped to the account level using/
.az cosmosdb sql role definition create \ --account-name <cosmosdb-account-name> \ --resource-group <resource-group-name> \ --body '{ "RoleName": "PasswordlessReadWrite", "Type": "CustomRole", "AssignableScopes": ["/"], "Permissions": [{ "DataActions": [ "Microsoft.DocumentDB/databaseAccounts/readMetadata", "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/*", "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/*" ] }] }'
When the command completes, copy the ID value from the
name
field and paste it somewhere for later use.Assign the role you created to the user account or service principal that will connect to Cosmos DB. During local development, this will generally be your own account that's logged into a development tool like Visual Studio or the Azure CLI. Retrieve the details of your account using the
az ad user
command.az ad user show --id "<your-email-address>"
Copy the value of the
id
property out of the results and paste it somewhere for later use.Assign the custom role you created to your user account using the
az cosmosdb sql role assignment create
command and the IDs you copied previously.az cosmosdb sql role assignment create \ --account-name <cosmosdb-account-name> \ --resource-group <resource-group-name> \ --scope "/" \ --principal-id <your-user-id> \ --role-definition-id <your-custom-role-id>
Authenticate using DefaultAzureCredential
For local development, make sure you're authenticated with the same Azure AD account you assigned the role to. You can authenticate via popular development tools, such as the Azure CLI or Azure PowerShell. The development tools with which you can authenticate vary across languages.
Sign-in to Azure through the Azure CLI using the following command:
az login
From the project directory, open the index.js file. In your editor, add npm packages to work with Cosmos DB and authenticate to Azure. You'll authenticate to Cosmos DB for NoSQL using DefaultAzureCredential
from the @azure/identity
package. DefaultAzureCredential
will automatically discover and use the account you signed-in with previously.
// Get Identity Client
import { DefaultAzureCredential } from "@azure/identity";
// Get Cosmos Client
import { CosmosClient } from "@azure/cosmos";
Create an environment variable that specifies your Cosmos DB endpoint.
// Provide required connection from environment variables
// Endpoint format: https://YOUR-RESOURCE-NAME.documents.azure.com:443/
const endpoint = process.env.COSMOS_ENDPOINT;
Create constants for the database and container names.
// Set Database name and container name with unique timestamp
const databaseName = `cosmicworks`;
const containerName = `products`;
Create a new client instance of the CosmosClient
class constructor with the DefaultAzureCredential
object and the endpoint.
// Authenticate to Azure Cosmos DB
const cosmosClient = new CosmosClient({
endpoint,
aadCredentials: new DefaultAzureCredential()
});
Create a database
The @azure/cosmos
client library enables you to perform data operations using Azure RBAC. However, to authenticate management operations, such as creating and deleting databases, you must use RBAC through one of the following options:
The Azure CLI approach is used in for this quickstart and passwordless access. Use the az cosmosdb sql database create
command to create a Cosmos DB for NoSQL database.
# Create a SQL API database `
az cosmosdb sql database create `
--account-name <cosmos-db-account-name> `
--resource-group <resource-group-name> `
--name cosmicworks
The command line to create a database is for PowerShell, shown on multiple lines for clarity. For other shell types, change the line continuation characters as appropriate. For example, for Bash, use backslash ("\"). Or, remove the continuation characters and enter the command on one line.
Create a container
The Microsoft.Azure.Cosmos
client library enables you to perform data operations using Azure RBAC. However, to authenticate management operations such as creating and deleting databases you must use RBAC through one of the following options:
The Azure CLI approach is used in this example. Use the az cosmosdb sql container create
command to create a Cosmos DB container.
# Create a SQL API container
az cosmosdb sql container create `
--account-name <cosmos-db-account-name> `
--resource-group <resource-group-name> `
--database-name cosmicworks `
--partition-key-path "/categoryId" `
--name products
The command line to create a container is for PowerShell, on multiple lines for clarity. For other shell types, change the line continuation characters as appropriate. For example, for Bash, use backslash ("\"). Or, remove the continuation characters and enter the command on one line. For Bash, you'll also need to add MSYS_NO_PATHCONV=1
before the command so that Bash deals with the partition key parameter correctly.
After the resources have been created, use classes from the Microsoft.Azure.Cosmos
client libraries to connect to and query the database.
Create an item
Add the following code to provide your data set. Each product has a unique ID, name, category id (used as partition key) and other fields.
// Data items
const items = [
{
"id": "08225A9E-F2B3-4FA3-AB08-8C70ADD6C3C2",
"categoryId": "75BF1ACB-168D-469C-9AA3-1FD26BB4EA4C",
"categoryName": "Bikes, Touring Bikes",
"sku": "BK-T79U-50",
"name": "Touring-1000 Blue, 50",
"description": "The product called \"Touring-1000 Blue, 50\"",
"price": 2384.0700000000002,
"tags": [
{
"_id": "27B7F8D5-1009-45B8-88F5-41008A0F0393",
"name": "Tag-61"
}
]
},
{
"id": "2C981511-AC73-4A65-9DA3-A0577E386394",
"categoryId": "75BF1ACB-168D-469C-9AA3-1FD26BB4EA4C",
"categoryName": "Bikes, Touring Bikes",
"sku": "BK-T79U-46",
"name": "Touring-1000 Blue, 46",
"description": "The product called \"Touring-1000 Blue, 46\"",
"price": 2384.0700000000002,
"tags": [
{
"_id": "4E102F3F-7D57-4CD7-88F4-AC5076A42C59",
"name": "Tag-91"
}
]
},
{
"id": "0F124781-C991-48A9-ACF2-249771D44029",
"categoryId": "56400CF3-446D-4C3F-B9B2-68286DA3BB99",
"categoryName": "Bikes, Mountain Bikes",
"sku": "BK-M68B-42",
"name": "Mountain-200 Black, 42",
"description": "The product called \"Mountain-200 Black, 42\"",
"price": 2294.9899999999998,
"tags": [
{
"_id": "4F67013C-3B5E-4A3D-B4B0-8C597A491EB6",
"name": "Tag-82"
}
]
}
];
Create a few items in the container by calling Container.Items.create
in a loop.
// Create all items
for (const item of items) {
const { resource } = await container.items.create(item);
console.log(`'${resource.name}' inserted`);
}
Get an item
In Azure Cosmos DB, you can perform a point read operation by using both the unique identifier (id
) and partition key fields. In the SDK, call Container.item().read
passing in both values to return an item.
The partition key is specific to a container. In this Contoso Products container, the category id, categoryId
, is used as the partition key.
// Read item by id and partitionKey - least expensive `find`
const { resource } = await container.item(items[0].id, items[0].categoryId).read();
console.log(`${resource.name} read`);
Query items
Add the following code to query for all items that match a specific filter. Create a parameterized query expression then call the Container.Items.query
method. This method returns a QueryIterator
that manages the pages of results. Then, use a combination of while
and for
loops to fetchNext
page of results as a FeedResponse
and then iterate over the individual data objects.
The query is programmatically composed to SELECT * FROM todo t WHERE t.partitionKey = 'Bikes, Touring Bikes'
.
// Query by SQL - more expensive `find`
// find all items with same categoryId (partitionKey)
const querySpec = {
query: "select * from products p where p.categoryId=@categoryId",
parameters: [
{
name: "@categoryId",
value: items[2].categoryId
}
]
};
// Get items
const { resources } = await container.items.query(querySpec).fetchAll();
for (const item of resources) {
console.log(`${item.id}: ${item.name}, ${item.sku}`);
}
If you want to use this data returned from the FeedResponse as an item, you need to create an Item
, using the Container.Items.read
method.
Delete an item
Add the following code to delete an item you need to use the ID and partition key to get the item, then delete it. This example uses the Container.Item.delete
method to delete the item.
// Delete item
const { statusCode } = await container.item(items[2].id, items[2].categoryId).delete();
console.log(`${items[2].id} ${statusCode==204 ? `Item deleted` : `Item not deleted`}`);
Run the code
This app creates an Azure Cosmos DB SQL API database and container. The example then creates items and then reads one item back. Finally, the example issues a query that should only return items matching a specific category. With each step, the example outputs metadata to the console about the steps it has performed.
To run the app, use a terminal to navigate to the application directory and run the application.
node index.js
The output of the app should be similar to this example:
contoso_1663276732626 database ready
products_1663276732626 container ready
'Touring-1000 Blue, 50' inserted
'Touring-1000 Blue, 46' inserted
'Mountain-200 Black, 42' inserted
Touring-1000 Blue, 50 read
08225A9E-F2B3-4FA3-AB08-8C70ADD6C3C2: Touring-1000 Blue, 50, BK-T79U-50
2C981511-AC73-4A65-9DA3-A0577E386394: Touring-1000 Blue, 46, BK-T79U-46
0F124781-C991-48A9-ACF2-249771D44029 Item deleted
Clean up resources
When you no longer need the API for NoSQL account, you can delete the corresponding resource group.
Next steps
In this quickstart, you learned how to create an Azure Cosmos DB SQL API account, create a database, and create a container using the JavaScript SDK. You can now dive deeper into the SDK to import more data, perform complex queries, and manage your Azure Cosmos DB SQL API resources.
Feedback
Submit and view feedback for