本指南可帮助你生成 Node.js 控制台应用程序以连接到 Azure DocumentDB 群集。 您准备开发环境,使用 Azure SDK for JavaScript 中的 @azure/identity 包进行身份验证,并针对数据库中的文档执行常见操作。
先决条件
Azure 订阅服务
- 如果没有 Azure 订阅,请创建 试用版
现有的 Azure DocumentDB 群集
- 如果没有群集,请 创建新群集
如需在本地运行 CLI 参考命令,请安装 Azure CLI。 如果在 Windows 或 macOS 上运行,请考虑在 Docker 容器中运行 Azure CLI。 有关详细信息,请参阅如何在 Docker 容器中运行 Azure CLI。
如果使用的是本地安装,请使用 az login 命令登录到 Azure CLI。 若要完成身份验证过程,请遵循终端中显示的步骤。 有关其他登录选项,请参阅使用 Azure CLI 登录。
出现提示时,请在首次使用时安装 Azure CLI 扩展。 有关扩展的详细信息,请参阅 将扩展与 Azure CLI 配合使用。
运行az version命令,以查看已安装的版本和依赖库。 若要升级到最新版本,请运行az upgrade。
为群集配置了 Microsoft Entra 身份验证,已授予标识
root角色。- 若要启用Microsoft Entra 身份验证, 请查看配置指南。
- 最新版本的 TypeScript。
配置控制台应用程序
接下来,创建新的控制台应用程序项目,并导入必要的库以向群集进行身份验证。
为你的项目创建一个新目录,并用
npm init初始化它。mkdir mongodb-app cd mongodb-app npm init -y在项目中设置 TypeScript。
npm install typescript ts-node @types/node --save-dev npx tsc --init为应用程序创建主 app.ts TypeScript 文件。
touch app.ts安装用于身份验证的
@azure/identity库。npm install @azure/identity安装
mongodb库。npm install mongodb
连接至群集
现在,使用 Azure.Identity 库获取一个 TokenCredential,以用于连接到您的群集。 官方 MongoDB 驱动程序具有一个特殊接口,必须实现该接口,以便从 Microsoft Entra 获取令牌,以便在连接到群集时使用。
在 JavaScript 文件顶部导入必要的模块。
import { MongoClient } from 'mongodb'; import { DefaultAzureCredential } from '@azure/identity';创建一个令牌回调函数,用于在需要时从
TokenCredential实例获取令牌。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), }; };设置群集名称变量以连接到 Azure DocumentDB 群集。
const clusterName = '<azure-cosmos-db-mongodb-vcore-cluster-name>';创建
DefaultAzureCredential实例。const credential = new DefaultAzureCredential();创建配置了 OpenID Connect (OIDC) 身份验证的 MongoDB 客户端。
client = new MongoClient(`mongodb+srv://${clusterName}.global.mongocluster.cosmos.azure.cn/`, { connectTimeoutMS: 120000, tls: true, retryWrites: true, authMechanism: 'MONGODB-OIDC', authMechanismProperties: { OIDC_CALLBACK: (params) => azureIdentityTokenCallback(params, credential), ALLOWED_HOSTS: ['*.azure.com'] } }); console.log('Client created');
在 TypeScript 文件的顶部导入必要的模块。
import { AccessToken, DefaultAzureCredential, TokenCredential } from '@azure/identity'; import { Collection, Db, Filter, FindCursor, MongoClient, OIDCCallbackParams, OIDCResponse, UpdateFilter, UpdateOptions, UpdateResult, WithId } from 'mongodb';创建一个令牌回调函数,用于在需要时从
TokenCredential实例获取令牌。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) }; };设置群集名称变量以连接到 Azure DocumentDB 群集。
const clusterName: string = '<azure-cosmos-db-mongodb-vcore-cluster-name>';创建
DefaultAzureCredential实例。const credential: TokenCredential = new DefaultAzureCredential();创建配置了 OpenID Connect (OIDC) 身份验证的 MongoDB 客户端。
const client = new MongoClient( `mongodb+srv://${clusterName}.global.mongocluster.cosmos.azure.cn/`, { connectTimeoutMS: 120000, tls: true, retryWrites: true, authMechanism: 'MONGODB-OIDC', authMechanismProperties: { OIDC_CALLBACK: (params: OIDCCallbackParams) => AzureIdentityTokenCallback(params, credential), ALLOWED_HOSTS: ['*.azure.com'] } }); console.log('Client created');
执行常见操作
最后,使用官方库对数据库、集合和文档执行常见任务。 在这里,你将使用相同的类和方法与 MongoDB 或 DocumentDB 进行交互来管理集合和项。
按名称获取对数据库的引用。
const databaseName = process.env.SETTINGS__DATABASENAME ?? 'cosmicworks'; console.log('Database pointer created');获取对集合的引用。
const collectionName = process.env.SETTINGS__COLLECTIONNAME ?? 'products'; console.log('Collection pointer created');使用
collection.updateOne创建文档,并将其更新插入到集合中。const filter = { _id: request.params._id }; const payload = { $set: document }; const options = { upsert: true }; var response = await collection.updateOne(filter, payload, options); if (response.acknowledged) { console.log(`Documents upserted count:\t${response.matchedCount}`); }使用
collection.findOne获取集合中的特定文档。const filter = { _id: request.params.id }; var document = await collection.findOne(filter, options); console.log(`Read document _id:\t${document._id}`);使用
collection.find查询匹配筛选条件的多个文档。var filter = { category: 'gear-surf-surfboards' }; var documents = collection.find(filter); for await (const document of documents) { console.log(`Found document:\t${JSON.stringify(document)}`); }完成后关闭 MongoDB 客户端连接。
await client.close();
按名称获取对数据库的引用。
const database: Db = client.db('<database-name>'); console.log('Database pointer created');获取对集合的引用。
const collection: Collection<Product> = database.collection<Product>('<collection-name>'); console.log('Collection pointer created');定义表示产品文档的接口。
interface Product { _id: string; category: string; name: string; quantity: number; price: number; clearance: boolean; }使用
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' }; var payload: UpdateFilter<Product> = { $set: document }; var options: UpdateOptions = { upsert: true }; var response: UpdateResult<Product> = await collection.updateOne(query, payload, options); if (response.acknowledged) { console.log(`Documents upserted count:\t${response.matchedCount}`); }使用
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 read_item: Product = response as Product; console.log(`Read document _id:\t${read_item._id}`);使用
collection.find查询匹配筛选条件的多个文档。var query: Filter<Product> = { category: 'gear-surf-surfboards' }; var response: FindCursor<WithId<Product>> = collection.find(query); for await (const document of response) { console.log(`Found document:\t${JSON.stringify(document)}`); }完成后关闭 MongoDB 客户端连接。
await client.close();