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. Without a credit card or an Azure subscription, you can set up a free Try Azure Cosmos DB 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

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) or Get-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.

  1. Sign in to the Azure portal.

  2. From the Azure portal menu or the Home page, select Create a resource.

  3. On the New page, search for and select Azure Cosmos DB.

  4. 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.

    Screenshot of select API option page for Azure Cosmos DB.

  5. 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.

    Screenshot of new account page for API for NoSQL.

  6. Select Review + create.

  7. 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.

  8. Select Go to resource to go to the Azure Cosmos DB account page.

    Screenshot of deployment page for API for NoSQL resource.

  9. From the API for NoSQL account page, select the Keys navigation menu option.

    Screenshot of an API for NoSQL account page. The Keys option is highlighted in the navigation menu.

  10. Record the values from the URI and PRIMARY KEY fields. You'll use these values in a later step.

    Screenshot of Keys page with various credentials for an API for NoSQL account.

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>"

Create a new JavaScript project

  1. Create a new Node.js application in an empty folder using your preferred terminal.

    npm init -y
    
  2. 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 the package

  1. Add the @azure/cosmos npm package to the Node.js project.

    npm install @azure/cosmos
    
  2. Add the dotenv npm package to read environment variables from a .env file.

    npm install dotenv
    

Create local development environment files

  1. Create a .gitignore file and add the following value to ignore your environment file and your node_modules. This configuration file ensures that only secure and relevant files are checked into source code.

    .env
    node_modules
    
  2. Create a .env file with the following variables:

    COSMOS_ENDPOINT=
    COSMOS_KEY=
    

Create a code file

Create an index.js and add the following boilerplate code to the file to read environment variables:

// Get environment variables from .env
import * as dotenv from 'dotenv';
dotenv.config();

Add dependency to client library

Add the following code at the end of the index.js file to include the required dependency to programmatically access Cosmos DB.

// Get Cosmos Client
import { CosmosClient } from "@azure/cosmos";

Add environment variables to code file

Add the following code at the end of the index.js file to include the required environment variables. The endpoint and key were found at the end of the account creation steps.

// Provide required connection from environment variables
const key = process.env.COSMOS_KEY;
// Endpoint format: https://YOUR-RESOURCE-NAME.documents.azure.com:443/
const endpoint = process.env.COSMOS_ENDPOINT;

Add variables for names

Add the following variables to manage unique database and container names and the partition key (pk).

// Uniqueness for database and container
const timeStamp = + new Date();

// Set Database name and container name with unique timestamp
const databaseName = `contoso_${timeStamp}`;
const containerName = `products_${timeStamp}`;
const partitionKeyPath = ["/categoryName"]

In this example, we chose to add a timeStamp to the database and container in case you run this sample code more than once.

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.

Diagram of the Azure Cosmos DB hierarchy including 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 adventureworks 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

In the index.js, add the following code to use the resource endpoint and key to authenticate to Cosmos DB. Define a new instance of the CosmosClient class.

// Authenticate to Azure Cosmos DB
const cosmosClient = new CosmosClient({ endpoint, key });

Create a database

Add the following code to use the CosmosClient.Databases.createDatabaseIfNotExists method to create a new database if it doesn't already exist. This method will return a reference to the existing or newly created database.

// Create database if it doesn't exist
const { database } = await cosmosClient.databases.createIfNotExists({ id: databaseName });
console.log(`${database.id} database ready`);

Create a container

Add the following code to create a container with the Database.Containers.createContainerIfNotExistsAsync method. The method returns a reference to the container.

// Create container if it doesn't exist
const { container } = await database.containers.createIfNotExists({
    id: containerName,
    partitionKey: {
        paths: partitionKeyPath
    }
});
console.log(`${container.id} container ready`);

Create an item

Add the following code to provide your data set. Each product has a unique ID, name, category name (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 name, categoryName, 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].categoryName).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 will manage 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 categoryName (partitionKey)
const querySpec = {
    query: "select * from products p where p.categoryName=@categoryName",
    parameters: [
        {
            name: "@categoryName",
            value: items[2].categoryName
        }
    ]
};

// 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].categoryName).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.

  1. Navigate to the resource group you previously created in the Azure portal.

    Tip

    In this quickstart, we recommended the name msdocs-cosmos-quickstart-rg.

  2. Select Delete resource group.

    Screenshot of the Delete resource group option in the navigation bar for a resource group.

  3. On the Are you sure you want to delete dialog, enter the name of the resource group, and then select Delete.

    Screenshot of the delete confirmation page for a 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.