Welcome to the Node.js SDK for Azure Cosmos DB
The Azure Cosmos DB Node.js SDK provides a powerful and intuitive way to interact with Azure Cosmos DB from your Node.js applications. Whether you're building a real-time web application, a mobile backend, or a microservice, this SDK simplifies data management and helps you leverage the full capabilities of Azure Cosmos DB.
Get StartedKey Features
Comprehensive APIs
Supports the SQL (Core) API for document and graph data, providing a familiar query language.
Asynchronous Operations
Leverages Node.js's async nature with Promises and async/await for non-blocking I/O.
High Performance
Optimized for low latency and high throughput, ensuring your application remains responsive.
Cross-Platform Compatibility
Works seamlessly on Windows, macOS, and Linux environments.
Change Feed Support
Easily process changes to your data in real-time for event-driven architectures.
Retry Logic
Built-in, configurable retry policies handle transient network issues automatically.
Getting Started
Follow these simple steps to begin using the Azure Cosmos DB Node.js SDK.
1. Installation
Install the SDK using npm:
npm install @azure/cosmos
2. Initialize Client
Connect to your Cosmos DB account.
const { CosmosClient } = require("@azure/cosmos");
// Replace with your actual connection string or endpoint and key
const endpoint = "YOUR_COSMOS_DB_ENDPOINT";
const key = "YOUR_COSMOS_DB_KEY";
const client = new CosmosClient({ endpoint, key });
3. Basic Operations
Create a database, container, and perform CRUD operations.
// Example: Creating a database and container
async function setupDatabase() {
const { database } = await client.databases.createIfNotExists({ id: "ToDoList" });
console.log(`Created/using database: ${database.id}`);
const { container } = await database.containers.createIfNotExists({ id: "Items" });
console.log(`Created/using container: ${container.id}`);
}
// Example: Inserting an item
async function addItem() {
const newItem = { id: "item1", category: "personal", name: "Groceries", description: "Buy milk and eggs" };
const { item } = await client.database("ToDoList").container("Items").items.create(newItem);
console.log(`Created item with id: ${item.id}`);
}
// Example: Querying items
async function queryItems() {
const querySpec = {
query: "SELECT * FROM c WHERE c.category = @category",
parameters: [{ name: "@category", value: "personal" }]
};
const { resources: items } = await client.database("ToDoList").container("Items").items.query(querySpec).fetchAll();
console.log("Found items:", items);
}
// Run the setup and operations
async function run() {
await setupDatabase();
await addItem();
await queryItems();
}
run().catch(error => {
console.error("An error occurred:", error);
});