How to read and write using Cosmos DB and NodeJS

1 min read

Azure Cosmos DB services

Learn how to perform basic read and write operations with Azure Cosmos DB using Node.js. This guide will help you set up and execute database interactions efficiently.

What is Cosmos DB?

Azure Cosmos DB, a database storage and management service that supports multiple data models (multi-model) and has global scalability, helps you quickly build a cloud database solution with high reliability.

This service provides easy and familiar SQL query features for users. Enjoy virtually unlimited throughput and storage, scale-out architectures for automatic elasticity, traditional scale-up of nodes, and consumption-based serverless options.

1. Prerequisites:

  • Node.js installed
  • Azure Cosmos DB account

Note: If you don’t have Azure Cosmos DB account, you can use Azure Cosmos DB Emulator instead and download by the link below:

https://learn.microsoft.com/en-us/azure/cosmos-db/how-to-develop-emulator?tabs=windows%2Ccsharp&pivots=api-nosql

Different between emulator and cloud services you can read:

https://learn.microsoft.com/en-us/azure/cosmos-db/emulator#differences-between-the-emulator-and-cloud-service

2. Install the Azure Cosmos DB SDK:

npm install @azure/cosmos

3. Connect Cosmos DB

Create config.js file to connect DB

module.exports = {
  endpoint: "YOUR_COSMOS_DB_ENDPOINT",
  key: "YOUR_COSMOS_DB_PRIMARY_KEY",
  databaseId: "YourDatabaseId",
  containerId: "YourContainerId",
};

Note: you can find in tab keys

4. Create CosmosClient

Create cosmosClient.js file

const { CosmosClient } = require("@azure/cosmos");
const config = require("./config");

const client = new CosmosClient({
  endpoint: config.endpoint,
  key: config.key,
});

const database = client.database(config.databaseId);
const container = database.container(config.containerId);

module.exports = container;

5. Writing Data to Cosmos DB

Create a cosmos.js file to insert data:

const container = require("./cosmosClient");

async function writeData() {
  const newItem = {
    id: "1",
    name: "Sample Item",
    description: "This is a sample item",
  };

  const { resource: createdItem } = await container.items.create(newItem);
  console.log(`Created item: ${createdItem.id} - ${createdItem.name}`);
}

writeData().catch((error) => {
  console.error(error);
});

6. Reading Data from Cosmos DB

Add read function to cosmos.js:

const container = require("./cosmosClient");

async function writeData() {
  const newItem = {
    id: "1",
    name: "Sample Item",
    description: "This is a sample item",
  };

  const { resource: createdItem } = await container.items.create(newItem);
  console.log(`Created item: ${createdItem.id} - ${createdItem.name}`);
}

async function readData() {
  const querySpec = {
    query: "SELECT * from c WHERE c.id = @id",
    parameters: [
      {
        name: "@id",
        value: "1",
      },
    ],
  };

  const { resources: items } = await container.items.query(querySpec).fetchAll();
  items.forEach((item) => {
    console.log(`${item.id} - ${item.name}: ${item.description}`);
  });
}

readData().catch((error) => {
  console.error(error);
});

Reference: https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/quickstart-nodejs?pivots=devcontainer-codespace

Avatar photo

Leave a Reply

Your email address will not be published. Required fields are marked *