DEV Community

Cover image for Getting Started with Azure Cosmos DB and Node.js: A Step-by-Step Guide
Oluwatobiloba Akinbobola
Oluwatobiloba Akinbobola

Posted on

Getting Started with Azure Cosmos DB and Node.js: A Step-by-Step Guide

INTRODUCTION

Microsoft Azure's fully managed NoSQL database solution, Azure Cosmos DB, gives you low latency, scalable, and highly available access to your data. We'll go over how to install the required tools, set up Azure Cosmos DB, and build a basic Node.js application to communicate with the database in this tutorial.

PROCEDURE

Step 1: Set Up Azure Cosmos DB
Before diving into coding, you must set up an Azure Cosmos DB account and create a database and container.
1.Create an Azure Cosmos DB Account:

  • Log in to the Azure Portal.
  • Search for "Azure Cosmos DB" and click Create. Azure Cosmos DB
  • Choose the Core (SQL) API and fill in the required details, such as the resource group, account name, and region. Core (SQL)
    • Click Review + Create, then Create to provision your account. Review + Create Create

2.Create a Database and Container:
Quick start

  • Navigate to Data Explorer in the Azure Portal once the account is ready.
  • Create a new database (e.g., ToDoListDB).
  • Inside the database, create a new container (e.g., Items) and set the partition key (e.g., /id). partion key

Step 2: Install Required Software on Your Local Machine
To build and run the Node.js application, you’ll need to install the following tools:

  1. Install Node.js:

    • Visit the Node.js official website and download the latest LTS version.
    • Install Node.js, which includes npm (Node Package Manager).
  2. Set Up Your Project:

    • Create a new directory for your project: Node
mkdir cosmosTest && cd cosmosTest
Enter fullscreen mode Exit fullscreen mode
  • Initialize a new Node.js project:
npm init -y
Enter fullscreen mode Exit fullscreen mode
  • Install the Azure Cosmos DB SDK:
npm install @azure/cosmos
Enter fullscreen mode Exit fullscreen mode

Step 3: Write a Simple Application to Connect to Cosmos DB
Now, let’s create a basic Node.js application to connect to your Cosmos DB instance.
1.Create a New File:

  • Open your project in VS Code and create a new file named app.js.

2.Write the Connection Code:

  • Add the following code to app.js:
const { CosmosClient } = require("@azure/cosmos");

const endpoint = "<your-cosmosdb-endpoint>";
const key = "<your-cosmosdb-key>";
const client = new CosmosClient({ endpoint, key });

const databaseId = "ToDoListDB";
const containerId = "Items";

async function run() {
    const database = client.database(databaseId);
    const container = database.container(containerId);

    // Test insertion
    const { resource: item } = await container.items.create({
        id: "1",
        description: "This is a test item",
        isCompleted: false,
    });
    console.log("Item created successfully: ", item.id);

    // Test retrieval
    const { resource: fetchedItem } = await container.item(item.id).read();
    console.log("Item fetched successfully: ", fetchedItem);
}

run().catch((error) => {
    console.error("Error occurred:", error);
});
Enter fullscreen mode Exit fullscreen mode

Nodejs

  • Replace <your-cosmosdb-endpoint> and <your-cosmosdb-key> with your actual Cosmos DB endpoint and key. These can be found in the Keys section of your Cosmos DB account in the Azure Portal. code Step 4: Run and Test the Application With the code in place, it’s time to run and test your application. 1.Run the Application:
  • In the terminal, navigate to your project directory and run:
node app.js
Enter fullscreen mode Exit fullscreen mode

2.Check the Output:

  • If everything is set up correctly, you should see output similar to:
Item created successfully: 1
Item fetched successfully: { id: 'Wakefield.7', description: 'This is a test item', isCompleted: false }
Enter fullscreen mode Exit fullscreen mode

3.Verify in Azure Portal:

  • Go to your Azure Cosmos DB account in the Azure Portal.
  • Navigate to Data Explorer > ToDoListDB > Items. Data Explorer
  • You should see the document created by your script. item

CONCLUSION

Well done! You have successfully installed the required tools, configured Azure Cosmos DB, and developed a basic Node.js application to communicate with your database.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay