共用方式為


建立一個使用 Azure DocumentDB 的 Node.js 主控台應用程式

本指南將協助你建立一個 Node.js 主控台應用程式,以連接 Azure DocumentDB 叢集。 您準備開發環境、使用 @azure/identity 適用於 JavaScript 的 Azure SDK 套件來驗證,以及在資料庫中的文件上執行一般作業。

先決條件

  • Azure 訂用帳戶

    • 如果您沒有 Azure 訂用帳戶,請建立 免費帳戶
  • 一個現有的 Azure DocumentDB 叢集

  • 您已被授予 root 角色的 Microsoft Entra 驗證已配置在叢集上。

  • 最新的節點長期支援 (LTS) 版本

設定主控台應用程式

接下來,建立新的主控台應用程式專案,並匯入必要的函式庫來驗證您的叢集。

  1. 為您的專案建立新的目錄,並使用 npm init 初始化它。

    mkdir mongodb-app
    cd mongodb-app
    npm init -y
    
  2. 在您的項目中設定 TypeScript。

    npm install typescript ts-node @types/node --save-dev
    npx tsc --init
    
  3. 為您的應用程式建立主要 app.ts TypeScript 檔案。

    touch app.ts
    
  4. 安裝 @azure/identity 庫以驗證身份。

    npm install @azure/identity
    
  5. 安裝 mongodb 程式庫。

    npm install mongodb
    

連接至叢集

現在,使用 Azure.Identity 庫取得 TokenCredential,以用來連線到您的叢集。 官方 MongoDB 驅動程式有一個特殊的介面,必須實作才能從 Microsoft Entra 取得令牌,以在連線到叢集時使用。

  1. 在 JavaScript 檔案頂端匯入必要的模組。

    import { MongoClient } from 'mongodb';
    import { DefaultAzureCredential } from '@azure/identity';
    
  2. 建立令牌回呼函式,以在需要時從 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),
        };
    };
    
  3. 設定你的叢集名稱變數,以連接到你的 Azure 文件資料庫叢集。

    const clusterName = '<azure-documentdb-cluster-name>';
    
  4. 建立 DefaultAzureCredential 執行個體。

    const credential = new DefaultAzureCredential();
    
  5. 建立使用 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');
    
  1. 在 TypeScript 檔案頂端匯入必要的模組。

    import { AccessToken, DefaultAzureCredential, TokenCredential } from '@azure/identity';
    import { Collection, Db, Filter, FindCursor, MongoClient, OIDCCallbackParams, OIDCResponse, UpdateFilter, UpdateOptions, UpdateResult, WithId } from 'mongodb';
    
  2. 建立令牌回呼函式,以在需要時從 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)
        };
    };
    
  3. 將您的叢集名稱變數設為與 Azure DocumentDB 叢集連接。

    const clusterName: string = '<azure-documentdb-cluster-name>';
    
  4. 建立 DefaultAzureCredential 執行個體。

    const credential: TokenCredential = new DefaultAzureCredential();
    
  5. 建立使用 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 互動的相同類別和方法來管理您的集合和專案。

  1. 依名稱取得您資料庫的參考。

    const databaseName = process.env.SETTINGS__DATABASENAME ?? 'cosmicworks';
    
    console.log('Database pointer created');
    
  2. 取得您集合的參考。

    const collectionName = process.env.SETTINGS__COLLECTIONNAME ?? 'products';
    
    console.log('Collection pointer created');
    
  3. 使用 collection.updateOne 建立文件,然後將其 upsert 到集合中。

    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}`);
    }
    
  4. 使用 collection.findOne 從集合取得特定檔。

    const filter = { _id: request.params.id };
    
    var document = await collection.findOne(filter, options);
    
    console.log(`Read document _id:\t${document._id}`);
    
  5. 使用 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)}`);
    }
    
  6. 完成時關閉 MongoDB 用戶端連線。

    await client.close();
    
  1. 依名稱取得您資料庫的參考。

    const database: Db = client.db('<database-name>');
    
    console.log('Database pointer created');
    
  2. 取得您集合的參考。

    const collection: Collection<Product> = database.collection<Product>('<collection-name>');
    
    console.log('Collection pointer created');
    
  3. 定義介面來代表您的產品檔。

    interface Product {
        _id: string;
        category: string;
        name: string;
        quantity: number;
        price: number;
        clearance: boolean;
    }
    
  4. 使用 collection.updateOne 建立文件,然後將其 upsert 到集合中。

    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}`);
    }
    
  5. 使用 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}`);
    
  6. 使用 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)}`);
    }
    
  7. 完成時關閉 MongoDB 用戶端連線。

    await client.close();