What is @azure/cosmos?
@azure/cosmos is an npm package that provides a client library for interacting with Azure Cosmos DB, a globally distributed, multi-model database service. The package allows developers to perform various database operations such as creating, reading, updating, and deleting databases, containers, and items. It also supports querying data using SQL-like syntax and managing throughput and indexing policies.
What are @azure/cosmos's main functionalities?
Create a Database
This feature allows you to create a new database in Azure Cosmos DB if it does not already exist. The code sample demonstrates how to initialize the CosmosClient and create a database named 'sample-database'.
const { CosmosClient } = require('@azure/cosmos');
const endpoint = 'your-endpoint';
const key = 'your-key';
const client = new CosmosClient({ endpoint, key });
async function createDatabase() {
const { database } = await client.databases.createIfNotExists({ id: 'sample-database' });
console.log(`Created database: ${database.id}`);
}
createDatabase().catch(console.error);
Create a Container
This feature allows you to create a new container within a specified database in Azure Cosmos DB. The code sample demonstrates how to create a container named 'sample-container' with a specified partition key.
const { CosmosClient } = require('@azure/cosmos');
const endpoint = 'your-endpoint';
const key = 'your-key';
const client = new CosmosClient({ endpoint, key });
async function createContainer() {
const database = client.database('sample-database');
const { container } = await database.containers.createIfNotExists({ id: 'sample-container', partitionKey: { kind: 'Hash', paths: ['/partitionKey'] } });
console.log(`Created container: ${container.id}`);
}
createContainer().catch(console.error);
Insert an Item
This feature allows you to insert a new item into a specified container in Azure Cosmos DB. The code sample demonstrates how to insert an item with an id, partition key, and name into the 'sample-container'.
const { CosmosClient } = require('@azure/cosmos');
const endpoint = 'your-endpoint';
const key = 'your-key';
const client = new CosmosClient({ endpoint, key });
async function insertItem() {
const container = client.database('sample-database').container('sample-container');
const item = { id: '1', partitionKey: 'partition1', name: 'Sample Item' };
const { resource } = await container.items.create(item);
console.log(`Inserted item: ${resource.id}`);
}
insertItem().catch(console.error);
Query Items
This feature allows you to query items in a specified container using SQL-like syntax. The code sample demonstrates how to query items with a specific partition key from the 'sample-container'.
const { CosmosClient } = require('@azure/cosmos');
const endpoint = 'your-endpoint';
const key = 'your-key';
const client = new CosmosClient({ endpoint, key });
async function queryItems() {
const container = client.database('sample-database').container('sample-container');
const querySpec = {
query: 'SELECT * FROM c WHERE c.partitionKey = @partitionKey',
parameters: [{ name: '@partitionKey', value: 'partition1' }]
};
const { resources: items } = await container.items.query(querySpec).fetchAll();
items.forEach(item => console.log(`Queried item: ${item.id}`));
}
queryItems().catch(console.error);
Other packages similar to @azure/cosmos
mongodb
The 'mongodb' package is a popular client library for interacting with MongoDB databases. Like @azure/cosmos, it allows for CRUD operations, querying, and managing collections. However, it is specific to MongoDB and does not offer the same level of global distribution and multi-model support as Azure Cosmos DB.
dynamodb
The 'dynamodb' package is an AWS SDK client for interacting with Amazon DynamoDB, a NoSQL database service. It provides similar functionalities such as creating tables, inserting items, and querying data. Unlike @azure/cosmos, it is tailored for use with AWS services and does not support multiple data models.
couchbase
The 'couchbase' package is a client library for interacting with Couchbase Server, a distributed NoSQL database. It offers features like document storage, querying, and indexing. While it provides similar capabilities to @azure/cosmos, it is designed specifically for Couchbase and does not offer the same level of global distribution.
Microsoft Azure Cosmos JavaScript SDK
This project provides JavaScript & Node.js SDK library for SQL API of Azure Cosmos
Database Service. This project also includes samples, tools, and utilities.
const cosmos = require('@azure/cosmos');
const CosmosClient = cosmos.CosmosClient;
const endpoint = "[hostendpoint]";
const masterKey = "[database account masterkey]";
const client = new CosmosClient({ endpoint, auth: { masterKey } });
const databaseDefinition = { id: 'sample database' };
const collectionDefinition = { id: 'sample collection' };
const documentDefinition = { id: 'hello world doc', content: 'Hello World!' };
async function helloCosmos() {
const { database: db } = await client.databases.create(databaseDefinition);
console.log('created db');
const { container } = await db.containers.create(collectionDefinition);
console.log('created collection');
const { body } = await container.items.create(documentDefinition);
console.log('Created item with content: ', body.content);
await db.delete();
console.log('Deleted database');
}
helloCosmos().catch(err => {
console.error(err);
});
Useful links
Installation
Prerequisites
Install Node.js 6 or above and npm
https://docs.npmjs.com/getting-started/installing-node
The SDK is not supported in Node v4 or below. Those Node.js versions are out of support and not recommended for production. Our support will only cover maintained versions of Node.js.
To use the SDK, first create an account and follow tutorial.
Note:
When connecting to the emulator from the SDK, SSL verification is disabled.
Follow these instructions to run the tests locally.
Install
npm install @azure/cosmos
Tests
Prerequisites
-
Clone Azure/azure-cosmos-js repository
git clone https://github.com/azure/azure-cosmos-js.git
-
Install Node.js 6 or above and npm
https://docs.npmjs.com/getting-started/installing-node
-
Cosmos DB emulator
- Note: requires a windows machine or ability to run Windows container
-
Install dependencies
npm i
-
Build the source
npm run build
Running the tests
npm run test
Need Help?
Tweet us with #CosmosDB and we'll respond on Twitter. Be sure to check out the Microsoft Azure Developer Forums on MSDN or the Developer Forums on Stack Overflow if you have trouble with the provided code.
Contribute Code or Provide Feedback
If you would like to become an active contributor to this project please follow the instructions provided in Azure Projects Contribution Guidelines.
If you encounter any bugs with the library please file an issue in the Issues section of the project.