共用方式為


快速入門:使用 Azure DocumentDB 並在 Node.js 中搭配 MongoDB 驅動程式

在這個快速入門中,你會用 Node.js建立一個基本的 Azure DocumentDB 應用程式。 Azure DocumentDB 是一個 NoSQL 資料儲存庫,允許應用程式將文件儲存在雲端,並透過官方 MongoDB 驅動程式存取。 本指南說明如何在 Azure DocumentDB 叢集中使用 Node.js建立文件並執行基本任務。

API 參考 | 原始碼 | 套件(npm)

先決條件

  • Azure 訂用帳戶

    • 如果您沒有 Azure 訂用帳戶,請建立 免費帳戶
  • Node.js 22 或更新

建立 Azure DocumentDB 叢集

要開始,你首先需要建立一個 Azure DocumentDB 叢集,作為儲存和管理 NoSQL 資料的基礎。

  1. 登入 Azure 入口網站https://portal.azure.com)。

  2. 從 Azure 入口網站功能表或 [首頁] 頁面,選取 [建立資源]

  3. 新頁面 搜尋並選擇 Azure DocumentDB

    搜尋 Azure DocumentDB 的截圖。

  4. 「建立 Azure DocumentDB 叢集」頁面及「基礎」區塊中,選擇叢集層級區塊中的「配置」選項。

    顯示「配置叢集」選項的截圖。

  5. 縮放 頁面中,設定這些選項,然後選擇 儲存 ,將你的變更永久化到叢集層級。

    價值觀
    叢集層 M30 tier, 2 vCore, 8-GiB RAM
    每個分區的儲存體 128 GiB

    新 Azure DocumentDB 叢集的運算與儲存設定選項截圖。

  6. 回到 基礎 部分,設定以下選項:

    價值觀
    Subscription 選取您的 Azure 訂用帳戶
    資源群組 建立新的資源群組,或選取現有的資源群組
    叢集名稱 提供全域唯一名稱
    地點 為您的訂用帳戶選取支援的 Azure 區域
    MongoDB 版本 選取 8.0
    系統管理員使用者名稱 建立使用者名稱以以使用者管理員身份存取叢集
    密碼 使用與使用者名稱相關的獨特密碼

    顯示叢集參數的截圖。

    小提示

    記錄你用來輸入 使用者名稱密碼的數值。 這些數值會在本指南後面使用。 關於有效數值的更多資訊,請參見 叢集限制

  7. 請選取「下一步:網路」。

  8. 網路標籤的防火牆規則區塊中,設定以下選項:

    價值觀
    連線方法 Public access
    允許從 Azure 內的服務和資源對此叢集進行公開存取 Enabled
  9. 為你目前的客戶端裝置新增防火牆規則,透過選擇 + 新增目前的客戶端 IP 位址來授權存取叢集。

    網路設定的截圖。

    小提示

    在許多公司環境中,開發人員機器 IP 位址會因為 VPN 或其他公司網路設定而遭到隱藏。 在這種情況下,你可以透過新增一個包含 0.0.0.0 - 255.255.255.255 的 IP 位址範圍至防火牆規則中,來暫時允許所有 IP 位址的存取。 此防火牆規則僅暫時用於連線測試與開發。

  10. 選擇 檢閱 + 創建

  11. 檢閱您提供的設定,然後選取 建立。 建立叢集需要幾分鐘的時間。 等待資源部署完成。

  12. 最後,選擇 「前往資源 」以導航至入口網站中的 Azure DocumentDB 叢集。

螢幕擷取畫面顯示 [移至資源] 選項。

取得叢集認證

取得你用來連接叢集的憑證。

  1. 在叢集頁面,選擇資源選單中的 連線字串 選項。

  2. Connection 字串 區塊,複製或記錄 Connection 字串 欄位的值。

有張顯示連線字串選項的截圖。

這很重要

入口網站中的連接字串不包含密碼值。 您必須將 <password> 佔位符替換為建立叢集時輸入的憑證,或以互動方式輸入密碼。

初始化專案

在你目前的目錄中建立一個新的 Node.js 專案。

  1. 從空白目錄開始。

  2. 在目前目錄中開啟終端機。

  3. 初始化一個 Node.js 專案。

    npm init -y
    
  4. 安裝 TypeScript 並初始化 TypeScript 設定(可選以支援 TypeScript)。

    npm install -D typescript @types/node
    npx tsc --init
    

安裝用戶端程式庫

用戶端程式庫可透過 npm 取得,作為 mongodb 套件。

  1. 使用 NPM 安裝 MongoDB Node.js 驅動程式。

    npm install mongodb
    
  2. 打開並檢視 package.json 檔案,確認套件條目是否存在。

  3. 將所需模組匯入您的應用程式代碼:

    import { MongoClient, Db, Collection, Document } from 'mongodb';
    
    const { MongoClient } = require('mongodb');
    

物件模型

名稱 Description
MongoClient 用來連線到 MongoDB 的類型。
Db 表示叢集中的資料庫。
Collection<Document> 表示叢集中資料庫內的集合。

程式碼範例

此應用程式中的程式碼連接一個名為 adventureworks 的資料庫與一個名為 products的集合。 該 products 收藏包含名稱、類別、數量、獨特識別碼及每項產品的銷售標誌等細節。 這裡的程式碼範例執行在處理集合時最常見的操作。

驗證用戶端

首先,使用基本的連接字串連接到用戶端。

  1. 建立主要函式並設定連接字串。 將<your-cluster-name><your-username><your-password>替換為您實際的叢集資訊。

    async function main(): Promise<void> {
        // Connection string for Azure DocumentDB cluster
        const connectionString = "mongodb+srv://<your-username>:<your-password>@<your-cluster-name>.global.mongocluster.cosmos.azure.com/?tls=true&authMechanism=SCRAM-SHA-256&retrywrites=false&maxIdleTimeMS=120000";
    
        // Create a new client and connect to the server
        const client = new MongoClient(connectionString);
    
    async function main() {
        // Connection string for Azure DocumentDB cluster
        const connectionString = "mongodb+srv://<your-username>:<your-password>@<your-cluster-name>.global.mongocluster.cosmos.azure.com/?tls=true&authMechanism=SCRAM-SHA-256&retrywrites=false&maxIdleTimeMS=120000";
    
        // Create a new client and connect to the server
        const client = new MongoClient(connectionString);
    
  2. 連接到 MongoDB 用戶端並驗證連線。

        try {
            // Connect to the MongoDB cluster
            await client.connect();
    
            // Ping the server to verify connection
            await client.db("admin").command({ ping: 1 });
            console.log("Successfully connected and pinged Azure DocumentDB");
    
        try {
            // Connect to the MongoDB cluster
            await client.connect();
    
            // Ping the server to verify connection
            await client.db("admin").command({ ping: 1 });
            console.log("Successfully connected and pinged Azure DocumentDB");
    

取得集合

現在,取得您的資料庫和集合。 如果資料庫和集合還不存在,可以用驅動程式自動幫你建立。

  1. 取得資料庫的參考資料。

            // Get database reference
            const database: Db = client.db("adventureworks");
            console.log(`Connected to database: ${database.databaseName}`);
    
            // Get database reference
            const database = client.db("adventureworks");
            console.log(`Connected to database: ${database.databaseName}`);
    
  2. 取得資料庫內的集合參考。

            // Get collection reference
            const collection: Collection<Document> = database.collection("products");
            console.log("Connected to collection: products");
    
            // Get collection reference
            const collection = database.collection("products");
            console.log("Connected to collection: products");
    

建立文件

接著,在你的收藏中新增幾份文件。 將文件 upsert 或更新,以確保若已存在具有相同唯一識別碼的文件,則會取代此文件。

  1. 製作範例產品文件。

            // Create sample products
            interface Product {
                _id: string;
                name: string;
                category: string;
                quantity: number;
                price: number;
                sale: boolean;
            }
    
            const products: Product[] = [
                {
                    _id: "00000000-0000-0000-0000-000000004018",
                    name: "Windry Mittens",
                    category: "apparel-accessories-gloves-and-mittens",
                    quantity: 121,
                    price: 35.00,
                    sale: false,
                },
                {
                    _id: "00000000-0000-0000-0000-000000004318",
                    name: "Niborio Tent",
                    category: "gear-camp-tents",
                    quantity: 140,
                    price: 420.00,
                    sale: true,
                }
            ];
    
            // Create sample products
            const products = [
                {
                    _id: "00000000-0000-0000-0000-000000004018",
                    name: "Windry Mittens",
                    category: "apparel-accessories-gloves-and-mittens",
                    quantity: 121,
                    price: 35.00,
                    sale: false,
                },
                {
                    _id: "00000000-0000-0000-0000-000000004318",
                    name: "Niborio Tent",
                    category: "gear-camp-tents",
                    quantity: 140,
                    price: 420.00,
                    sale: true,
                }
            ];
    
  2. 使用 upsert 作業插入文件。

            // Insert documents with upsert
            for (const product of products) {
                const filter = { _id: product._id };
                const options = { upsert: true };
    
                await collection.replaceOne(filter, product, options);
                console.log(`Upserted product: ${product.name}`);
            }
    
            // Insert documents with upsert
            for (const product of products) {
                const filter = { _id: product._id };
                const options = { upsert: true };
    
                await collection.replaceOne(filter, product, options);
                console.log(`Upserted product: ${product.name}`);
            }
    

擷取文件

接著,執行點讀取操作,從你的收藏中擷取特定文件。

  1. 定義篩選器,透過 ID 尋找特定文件。

            // Retrieve a specific document by ID
            const filter = { _id: "00000000-0000-0000-0000-000000004018" };
    
            // Retrieve a specific document by ID
            const filter = { _id: "00000000-0000-0000-0000-000000004018" };
    
  2. 執行查詢並取得結果。

            const retrievedProduct = await collection.findOne(filter);
    
            if (retrievedProduct) {
                console.log(`Retrieved product: ${retrievedProduct.name} - $${retrievedProduct.price}`);
            } else {
                console.log("Product not found");
            }
    
            const retrievedProduct = await collection.findOne(filter);
    
            if (retrievedProduct) {
                console.log(`Retrieved product: ${retrievedProduct.name} - $${retrievedProduct.price}`);
            } else {
                console.log("Product not found");
            }
    

查詢文件

最後,使用 MongoDB 查詢語言(MQL)查詢多份文件。

  1. 定義一個查詢以尋找符合特定條件的文件。

            // Query for products on sale
            const saleFilter = { sale: true };
            const saleProducts = await collection.find(saleFilter).toArray();
    
            // Query for products on sale
            const saleFilter = { sale: true };
            const saleProducts = await collection.find(saleFilter).toArray();
    
  2. 反覆檢視結果以顯示符合條件的文件。

            console.log("Products on sale:");
            for (const product of saleProducts) {
                console.log(`- ${product.name}: $${product.price.toFixed(2)} (Category: ${product.category})`);
            }
    
        } catch (error) {
            console.error("An error occurred:", error);
        } finally {
            await client.close();
        }
    }
    
    main().catch(console.error);
    
            console.log("Products on sale:");
            for (const product of saleProducts) {
                console.log(`- ${product.name}: $${product.price.toFixed(2)} (Category: ${product.category})`);
            }
    
        } catch (error) {
            console.error("An error occurred:", error);
        } finally {
            await client.close();
        }
    }
    
    main().catch(console.error);
    

使用 Visual Studio Code 探索您的資料

在 Visual Studio Code 中使用 DocumentDB 擴充功能來執行核心資料庫操作,包括查詢、插入、更新及刪除資料。

  1. 開啟 Visual Studio Code

  2. 請導覽至 擴充功能 檢視並搜尋該詞 DocumentDB。 請找到 DocumentDB for VS Code 擴充功能

  3. 選擇擴充功能的 安裝 按鈕。 等候安裝完成。 如果系統提示,請重新載入 Visual Studio Code。

  4. 請在活動欄中選擇對應圖示,導向 DocumentDB 擴充功能。

  5. DocumentDB 連接 面板中,選擇 + 新連線...

  6. 在對話框中,選擇 Service Discovery ,然後選擇 Azure DocumentDB - Azure Service Discovery

  7. 選擇您的 Azure 訂閱及新建立的 Azure DocumentDB 叢集。

    小提示

    在許多公司環境中,開發人員機器 IP 位址會因為 VPN 或其他公司網路設定而遭到隱藏。 在這種情況下,你可以透過新增一個包含 0.0.0.0 - 255.255.255.255 的 IP 位址範圍至防火牆規則中,來暫時允許所有 IP 位址的存取。 此防火牆規則僅暫時用於連線測試與開發。 如需詳細資訊,請參閱 設定防火牆

  8. 回到 DocumentDB 的連接 面板,展開叢集節點,並導覽到現有的文件和集合節點。

  9. 打開該收藏的右鍵選單,然後選擇 DocumentDB 剪貼簿 > 新設 DocumentDB 剪貼簿

  10. 輸入以下 MongoDB 查詢語言(MQL)指令,然後選擇「全部執行」。 觀察指令的輸出。

    db.products.find({
      price: { $gt: 200 },
      sale: true
    })
    .sort({ price: -1 })
    .limit(3)
    

清理資源

完成 Azure DocumentDB 叢集後,你可以刪除你建立的 Azure 資源,避免額外收費。

  1. 在 Azure 入口網站的搜尋列中,搜尋並選取 [資源群組]

    截圖顯示搜尋資源群組的選項。

  2. 在清單中,選取您在此快速入門中使用的資源群組。

    顯示資源群組的截圖。

  3. 在 [資源群組] 頁面中,選取 [刪除資源群組]。

  4. 在刪除確認對話方塊中,輸入資源群組的名稱,以確認您要將其刪除。 最後,選取 [刪除] 以永久刪除資源群組。

    截圖顯示刪除資源群組確認按鈕。