このガイドは、Azure Cosmos DB for MongoDB 仮想コア クラスターに接続する Node.js コンソール アプリケーションを構築するのに役立ちます。 開発環境を準備し、Azure SDK for JavaScript の @azure/identity
パッケージを使用して認証し、データベース内のドキュメントに対して一般的な操作を実行します。
[前提条件]
- 既存の Azure Cosmos DB for MongoDB (仮想コア) クラスター。
Azure Cloud Shell の Azure CLI の最新バージョン。
- CLI 参照コマンドをローカルで実行する場合は、
az login
コマンドを使用して Azure CLI にサインインします。
- CLI 参照コマンドをローカルで実行する場合は、
クラスター用に構成された Microsoft Entra 認証で、あなたの ID に
dbOwner
ロールが付与されています。- Microsoft Entra 認証を有効にするには、 構成ガイドを確認します。
Node の最新の長期サポート (LTS) バージョン
- TypeScript の最新バージョン。
コンソール アプリケーションを構成する
次に、新しいコンソール アプリケーション プロジェクトを作成し、クラスターに対して認証するために必要なライブラリをインポートします。
プロジェクトの新しいディレクトリを作成し、
npm init
で初期化します。mkdir cosmos-mongodb-app cd cosmos-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.windows.net/.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 Cosmos DB for MongoDB 仮想コア クラスターに接続するようにクラスター名変数を設定します。
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.com/`, { 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.windows.net/.default']); return { accessToken: tokenResponse?.token || '', expiresInSeconds: (tokenResponse?.expiresOnTimestamp || 0) - Math.floor(Date.now() / 1000) }; };
Azure Cosmos DB for MongoDB 仮想コア クラスターに接続するようにクラスター名変数を設定します。
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.com/`, { 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();