在本快速入门中,你将使用 Node.js部署基本的 Azure Cosmos DB for MongoDB 应用程序。 Azure Cosmos DB for MongoDB vCore 是一种无架构数据存储,允许应用程序使用 MongoDB 库将非结构化文档存储在云中。 了解如何使用 Node.js在 Azure Cosmos DB 资源中创建文档和执行基本任务。
库源代码 | 包 (npm) | Azure Developer CLI
Azure 开发人员 CLI
Docker Desktop
Azure 订阅服务
- 如果没有 Azure 订阅,可在开始前创建一个试用帐户。
- Node.js 22 或更高版本
使用 Azure 开发人员 CLI (azd
) 创建 Azure Cosmos DB for MongoDB vCore 群集并部署容器化示例应用程序。 示例应用程序使用客户端库来管理、创建、读取和查询示例数据。
在空目录中打开终端。
如果尚未经过身份验证,请使用
azd auth login
向 Azure Developer CLI 进行身份验证。 按照工具指定的步骤,使用首选的 Azure 凭据向 CLI 进行身份验证。azd auth login
使用
azd init
来初始化项目。azd init --template cosmos-db-mongodb-vcore-nodejs-quickstart
在初始化期间,配置唯一的环境名称。
使用
azd up
. 部署群集。 Bicep 模板还部署示例 Web 应用程序。azd up
在预配过程中,选择订阅、所需位置和目标资源组。 等待预配过程完成。 此过程可能需要 大约十分钟的时间。
预配 Azure 资源后,输出中将包含正在运行的 Web 应用程序的 URL。
Deploying services (azd deploy) (✓) Done: Deploying service web - Endpoint: <https://[container-app-sub-domain].azurecontainerapps.io> SUCCESS: Your application was provisioned and deployed to Azure in 5 minutes 0 seconds.
使用控制台中的 URL 在浏览器中导航到 Web 应用程序。 观察正在运行的应用的输出。
客户端库可通过 npm 作为 mongodb
包使用。
打开终端并导航到
/src/ts
文件夹。cd ./src/ts
使用
mongodb
安装npm install
包(如果尚未安装)。npm install --save mongodb
使用
@azure/identity
安装npm install
包(如果尚未安装)。npm install --save @azure/identity
打开并查看 src/ts/package.json 文件,以验证这两个包条目是否存在。
打开终端并导航到
/src/js
文件夹。cd ./src/js
使用
mongodb
安装npm install
包(如果尚未安装)。npm install --save mongodb
使用
@azure/identity
安装npm install
包(如果尚未安装)。npm install --save @azure/identity
打开并查看 src/js/package.json 文件,以验证这两个包条目是否存在。
将以下命名空间导入应用程序代码:
包装 | 来源 | |
---|---|---|
TokenCredential |
@azure/identity |
用于 JavaScript 的 Azure SDK |
DefaultAzureCredential |
@azure/identity |
用于 JavaScript 的 Azure SDK |
MongoClient |
mongodb |
用于 Node.js 的官方 MongoDB 驱动程序 |
import { DefaultAzureCredential, TokenCredential } from '@azure/identity';
import { MongoClient } from 'mongodb';
将所有必需的类型导入应用程序代码,包括但不限于:
包装 | 来源 | |
---|---|---|
TokenCredential |
@azure/identity |
用于 JavaScript 的 Azure SDK |
DefaultAzureCredential |
@azure/identity |
用于 JavaScript 的 Azure SDK |
MongoClient |
mongodb |
用于 Node.js 的官方 MongoDB 驱动程序 |
import { AccessToken, DefaultAzureCredential, TokenCredential } from '@azure/identity';
import { Collection, Db, Filter, FindCursor, MongoClient, OIDCCallbackParams, OIDCResponse, UpdateFilter, UpdateOptions, UpdateResult, WithId } from 'mongodb';
名称 | DESCRIPTION |
---|---|
MongoClient | 用于连接到 MongoDB 的类型。 |
Database |
表示群集中的数据库。 |
Collection |
表示群集中数据库内的集合。 |
模板中的示例代码使用名为 cosmicworks
的数据库和名为 products
的集合。
products
集合包含每个产品的名称、类别、数量和唯一标识符等详细信息。 该集合使用 /category
属性作为分片键。
虽然 Azure Cosmos DB for MongoDB vCore 的 Microsoft Entra 身份验证可以使用众所周知的 TokenCredential
类型,但你必须实现自定义令牌处理程序。 此示例实现可用于创建 MongoClient
,以支持多种标识类型的标准 Microsoft Entra 身份验证。
首先,定义一个名为
AzureIdentityTokenCallback
的回调,该回调接收OIDCCallbackParams
和TokenCredential
,然后异步返回一个OIDCResponse
。const AzureIdentityTokenCallback = async (params: OIDCCallbackParams, credential: TokenCredential): Promise<OIDCResponse> => { const tokenResponse: AccessToken | null = await credential.getToken(['https://ossrdbms-aad.database.chinacloudapi.cn/.default']); return { accessToken: tokenResponse?.token || '', expiresInSeconds: (tokenResponse?.expiresOnTimestamp || 0) - Math.floor(Date.now() / 1000) }; };
为群集名称和令牌凭据定义变量。
const clusterName: string = '<azure-cosmos-db-mongodb-vcore-cluster-name>'; const credential: TokenCredential = new DefaultAzureCredential();
使用您的群集名称和适用于 MongoDB vCore 的 Azure Cosmos DB 已知最佳实践配置选项来构建
MongoClient
实例。 此外,请配置自定义身份验证机制。const client = new MongoClient( `mongodb+srv://${clusterName}.global.mongocluster.cosmos.azure.com/`, { connectTimeoutMS: 120000, tls: true, retryWrites: true, authMechanism: 'MONGODB-OIDC', authMechanismProperties: { OIDC_CALLBACK: (params: OIDCCallbackParams) => AzureIdentityTokenCallback(params, credential), ALLOWED_HOSTS: ['*.azure.com'] } } );
首先,定义一个回调
azureIdentityTokenCallback
,该回调采用参数和令牌凭据,然后异步返回响应。const azureIdentityTokenCallback = async (_, credential) => { const tokenResponse = await credential.getToken(['https://ossrdbms-aad.database.chinacloudapi.cn/.default']); if (!tokenResponse || !tokenResponse.token) { throw new Error('Failed to retrieve a valid access token.'); } return { accessToken: tokenResponse.token, expiresInSeconds: Math.floor((tokenResponse.expiresOnTimestamp - Date.now()) / 1000), }; };
为群集名称和令牌凭据定义变量。
const clusterName = '<azure-cosmos-db-mongodb-vcore-cluster-name>'; const credential = new DefaultAzureCredential();
使用您的群集名称和适用于 MongoDB vCore 的 Azure Cosmos DB 已知最佳实践配置选项来构建
MongoClient
实例。 此外,请配置自定义身份验证机制。client = new MongoClient(`mongodb+srv://${clusterName}.global.mongocluster.cosmos.azure.com/`, { connectTimeoutMS: 120000, tls: true, retryWrites: true, authMechanism: 'MONGODB-OIDC', authMechanismProperties: { OIDC_CALLBACK: (params) => azureIdentityTokenCallback(params, credential), ALLOWED_HOSTS: ['*.azure.com'] } }); await client.connect();
此示例使用 Db
类型的 db
函数创建 MongoClient
类型的实例。
const database: Db = client.db("<database-name>");
const database = client.db("<database-name>");
此示例使用 Collection
类型的 collection
函数创建 Db
类型的实例。
此函数具有一个泛型参数,该参数使用接口中定义的 Product
类型。
const collection: Collection<Product> = database.collection<Product>("<collection-name>");
export interface Product {
_id: string;
category: string;
name: string;
quantity: number;
price: number;
clearance: boolean;
}
const collection = database.collection("<collection-name>");
使用 collection.updateOne
在集合中创建文档。 如果该项已经存在,此方法会“更新插入”该项,从而有效地替换该项。
var document: Product = {
_id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb',
category: 'gear-surf-surfboards',
name: 'Yamba Surfboard',
quantity: 12,
price: 850.00,
clearance: false
};
var query: Filter<Product> = {
_id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb',
category: 'gear-surf-surfboards'
};
var payload: UpdateFilter<Product> = {
$set: document
};
var options: UpdateOptions = {
upsert: true
};
var response: UpdateResult<Product> = await collection.updateOne(query, payload, options);
var document = {
_id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb',
category: 'gear-surf-surfboards',
name: 'Yamba Surfboard',
quantity: 12,
price: 850.00,
clearance: false
};
const query = {
_id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb',
category: 'gear-surf-surfboards'
};
const payload = {
$set: document
};
const options = {
upsert: true,
new: true
};
var response = await collection.updateOne(query, payload, options);
同时使用唯一标识符 (id
) 和分片键字段来执行点读取操作。 使用 collection.findOne
以有效检索特定项。
var query: Filter<Product> = {
_id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb',
category: 'gear-surf-surfboards'
};
var response: WithId<Product> | null = await collection.findOne(query);
var query = {
_id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb',
category: 'gear-surf-surfboards'
};
var response = await collection.findOne(query);
使用 collection.find
对容器中的多个项执行查询。 此查询查找指定类别(分片键)中的所有项。
var query: Filter<Product> = {
category: 'gear-surf-surfboards'
};
var response: FindCursor<WithId<Product>> = collection.find(query);
for await (const item of response) {
// Do something with each item
}
var query = {
category: 'gear-surf-surfboards'
};
var response = collection.find(query);
for await (const item of response) {
// Do something with each item
}
通过发送一个包含文档唯一标识符的筛选器来删除文档。 使用 collection.deleteOne<>
来异步地将文档从集合中删除。
var filter: Filter<Product> = {
_id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb'
};
await collection.deleteOne(filter);
const filter = {
_id: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb'
};
await collection.deleteOne(filter);
使用适用于 Azure Cosmos DB 的 Visual Studio Code 扩展浏览 MongoDB vCore 数据。 可以执行核心数据库操作,这些操作包括但不限于:
- 使用剪贴簿或查询编辑器执行查询
- 修改、更新、创建和删除文档
- 从其他源导入批量数据
- 管理数据库和集合
有关详细信息,请参阅 如何使用 Visual Studio Code 扩展浏览 Azure Cosmos DB for MongoDB vCore 数据。
不再需要示例应用程序或资源时,请删除相应的部署和所有资源。
azd down --force