快速入門:將現有的 MongoDB Node.js Web 應用程式遷移至 Azure Cosmos DBQuickstart: Migrate an existing MongoDB Node.js web app to Azure Cosmos DB

本快速入門示範如何使用以 Node.js 撰寫的現有 MongoDB 應用程式,並將它連線到可支援 MongoDB 用戶端的 Azure Cosmos 資料庫。This quickstart demonstrates how to use an existing MongoDB app written in Node.js and connect it to your Azure Cosmos database, which supports MongoDB client. 換句話說,對於資料儲存在 Cosmos 資料庫中的應用程式而言是透明的。In other words, it is transparent to the application that the data is stored in a Cosmos database.

Azure Cosmos DB 是 Microsoft 的全域分散式多模型資料庫服務。Azure Cosmos DB is Microsoft’s globally distributed multi-model database service. 您可以快速建立及查詢文件、索引鍵/值及圖形資料庫,所有這些都受惠於位於 Cosmos DB 核心的全域散發和水平調整功能。You can quickly create and query document, key/value, and graph databases, all of which benefit from the global distribution and horizontal scale capabilities at the core of Cosmos DB.

完成之後,MEAN 應用程式 (MongoDB、Express、Angular 及 Node.js) 便會在 Cosmos DB 上執行。When you are done, you will have a MEAN application (MongoDB, Express, Angular, and Node.js) running on Cosmos DB.

在 Azure App Service 中執行的 MEAN.js 應用程式

使用 Azure Cloud ShellUse Azure Cloud Shell

Azure Cloud Shell 是裝載於 Azure 中的互動式殼層環境,可在瀏覽器中使用。Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. 您可以使用 Bash 或 PowerShell 搭配 Cloud Shell,與 Azure 服務共同使用。You can use either Bash or PowerShell with Cloud Shell to work with Azure services. Azure Cloud Shell 已預先安裝一些命令,可讓您執行本文提到的程式碼,而不必在本機環境上安裝任何工具。You can use the Cloud Shell preinstalled commands to run the code in this article without having to install anything on your local environment.

要啟動 Azure Cloud Shell:To start Azure Cloud Shell:

選項Option 範例/連結Example/Link
選取程式碼區塊右上角的 [試試看] 。Select Try It in the upper-right corner of a code block. 選取 [試用] 並不會自動將程式碼複製到 Cloud Shell 中。Selecting Try It doesn't automatically copy the code to Cloud Shell. Azure Cloud Shell 的試試看範例
請前往 https://shell.azure.com 或選取 [啟動 Cloud Shell] 按鈕,在瀏覽器中開啟 Cloud Shell。Go to https://shell.azure.com, or select the Launch Cloud Shell button to open Cloud Shell in your browser. 在新視窗中啟動 Cloud ShellLaunch Cloud Shell in a new window
選取 Azure 入口網站右上角功能表列中的 [Cloud Shell] 按鈕。Select the Cloud Shell button on the top-right menu bar in the Azure portal. Azure 入口網站中的 [Cloud Shell] 按鈕

若要在 Azure Cloud Shell 中執行本文中的程式碼:To run the code in this article in Azure Cloud Shell:

  1. 啟動 Cloud Shell。Start Cloud Shell.

  2. 選取程式碼區塊上的 [複製] 按鈕,複製程式碼。Select the Copy button on a code block to copy the code.

  3. 在 Windows 和 Linux 上選取 Ctrl+Shift+V;或在 macOS 上選取 Cmd+Shift+V,將程式碼貼到 Cloud Shell 工作階段中。Paste the code into the Cloud Shell session by selecting Ctrl+Shift+V on Windows and Linux or by selecting Cmd+Shift+V on macOS.

  4. 選取 Enter 鍵執行程式碼。Select Enter to run the code.

如果您選擇在本機安裝和使用 CLI,本主題會要求您執行 Azure CLI 2.0 版或更新版本。If you choose to install and use the CLI locally, this topic requires that you are running the Azure CLI version 2.0 or later. 執行 az --version 以尋找版本。Run az --version to find the version. 如果您需要安裝或升級,請參閱安裝 Azure CLIIf you need to install or upgrade, see Install Azure CLI.

必要條件Prerequisites

如果您沒有 Azure 訂用帳戶,請在開始前建立 免費帳戶If you don't have an Azure subscription, create a free account before you begin.

或者,您可以免費試用 Azure Cosmos DB,無須 Azure 訂用帳戶,也無須任何費用和約定付款。Alternatively, you can Try Azure Cosmos DB for free without an Azure subscription, free of charge and commitments. 或者,您可以使用 Azure Cosmos DB 模擬器來進行本教學課程,連接字串為Or you can use the Azure Cosmos DB Emulator for this tutorial with a connection string of

mongodb://localhost:C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==@localhost:10255/admin?ssl=true

除了 Azure CLI,您還需要在本機安裝 Node.jsGit,才能執行 npmgit 命令。In addition to Azure CLI, you need Node.js and Git installed locally to run npm and git commands.

您應具備 Node.js 的使用知識。You should have working knowledge of Node.js. 本快速入門通常不是為了協助您開發 Node.js 應用程式。This quickstart is not intended to help you with developing Node.js applications in general.

複製範例應用程式Clone the sample application

執行下列命令來複製範例存放庫。Run the following commands to clone the sample repository. 此範例存放庫包含預設 MEAN.js 應用程式。This sample repository contains the default MEAN.js application.

  1. 開啟命令提示字元,建立名為 git-samples 的新資料夾,然後關閉命令提示字元。Open a command prompt, create a new folder named git-samples, then close the command prompt.

    mkdir "C:\git-samples"
    
  2. 開啟 git 終端機視窗 (例如 git bash),並使用 cd 命令變更至要安裝範例應用程式的新資料夾。Open a git terminal window, such as git bash, and use the cd command to change to the new folder to install the sample app.

    cd "C:\git-samples"
    
  3. 執行下列命令來複製範例存放庫。Run the following command to clone the sample repository. 此命令會在您的電腦上建立範例應用程式副本。This command creates a copy of the sample app on your computer.

    git clone https://github.com/prashanthmadi/mean
    

執行應用程式Run the application

安裝必要的封裝,然後啟動應用程式。Install the required packages and start the application.

cd mean
npm install
npm start

應用程式會嘗試連線到 MongoDB 來源且失敗,當輸出傳回 "[MongoError: connect ECONNREFUSED 127.0.0.1:27017]" 時,請繼續結束應用程式。The application will try to connect to a MongoDB source and fail, go ahead and exit the application when the output returns "[MongoError: connect ECONNREFUSED 127.0.0.1:27017]".

登入 AzureLog in to Azure

如果您要使用已安裝的 Azure CLI,請使用 az login 命令來登入 Azure 訂用帳戶,並遵循畫面上的指示進行。If you are using an installed Azure CLI, log in to your Azure subscription with the az login command and follow the on-screen directions. 如果您是使用 Azure Cloud Shell,可以跳過此步驟。You can skip this step if you're using the Azure Cloud Shell.

az login 

新增 Azure Cosmos DB 模組Add the Azure Cosmos DB module

如果您是使用已安裝的 Azure CLI,請檢查是否已安裝 cosmosdb 元件,方法是執行 az 命令。If you are using an installed Azure CLI, check to see if the cosmosdb component is already installed by running the az command. 如果 cosmosdb 位於基底命令清單中,請繼續進行下一個命令。If cosmosdb is in the list of base commands, proceed to the next command. 如果您是使用 Azure Cloud Shell,可以跳過此步驟。You can skip this step if you're using the Azure Cloud Shell.

如果 cosmosdb 不在基底命令的清單中,請重新安裝 Azure CLIIf cosmosdb is not in the list of base commands, reinstall Azure CLI.

建立資源群組Create a resource group

使用 az group create 來建立資源群組Create a resource group with the az group create. Azure 資源群組是在其中部署與管理 Azure 資源 (如 Web 應用程式、資料庫和儲存體帳戶) 的邏輯容器。An Azure resource group is a logical container into which Azure resources like web apps, databases and storage accounts are deployed and managed.

下列範例會在西歐區域中建立一個資源群組。The following example creates a resource group in the West Europe region. 選擇資源群組的唯一名稱。Choose a unique name for the resource group.

如果您是使用 Azure Cloud Shell,請選取 [試用] 、遵循畫面上的提示登入,然後將命令複製到命令提示字元。If you are using Azure Cloud Shell, select Try It, follow the onscreen prompts to login, then copy the command into the command prompt.

az group create --name myResourceGroup --location "West Europe"

建立 Azure Cosmos DB 帳戶Create an Azure Cosmos DB account

使用 az cosmosdb create 命令來建立 Cosmos 帳戶。Create a Cosmos account with the az cosmosdb create command.

在下列命令中,請在您看見 <cosmosdb-name> 預留位置的地方,替代成您自己的唯一 Cosmos 帳戶名稱。In the following command, please substitute your own unique Cosmos account name where you see the <cosmosdb-name> placeholder. 這個唯一名稱會作為 Cosmos DB 端點 https://<cosmosdb-name>.documents.azure.com/ 的一部分,因此,這個名稱在 Azure 中的所有 Cosmos 帳戶上必須是唯一的。This unique name will be used as part of your Cosmos DB endpoint (https://<cosmosdb-name>.documents.azure.com/), so the name needs to be unique across all Cosmos accounts in Azure.

az cosmosdb create --name <cosmosdb-name> --resource-group myResourceGroup --kind MongoDB

--kind MongoDB 參數會啟用 MongoDB 用戶端連接。The --kind MongoDB parameter enables MongoDB client connections.

建立 Azure Cosmos DB 帳戶之後,Azure CLI 會顯示類似下列範例的資訊。When the Azure Cosmos DB account is created, the Azure CLI shows information similar to the following example.

注意

此範例會使用 JSON 作為 Azure CLI 輸出格式,這是預設值。This example uses JSON as the Azure CLI output format, which is the default. 若要使用另一種輸出格式,請參閱 Azure CLI 命令的輸出格式To use another output format, see Output formats for Azure CLI commands.

{
  "databaseAccountOfferType": "Standard",
  "documentEndpoint": "https://<cosmosdb-name>.documents.azure.com:443/",
  "id": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Document
DB/databaseAccounts/<cosmosdb-name>",
  "kind": "MongoDB",
  "location": "West Europe",
  "name": "<cosmosdb-name>",
  "readLocations": [
    {
      "documentEndpoint": "https://<cosmosdb-name>-westeurope.documents.azure.com:443/",
      "failoverPriority": 0,
      "id": "<cosmosdb-name>-westeurope",
      "locationName": "West Europe",
      "provisioningState": "Succeeded"
    }
  ],
  "resourceGroup": "myResourceGroup",
  "type": "Microsoft.DocumentDB/databaseAccounts",
  "writeLocations": [
    {
      "documentEndpoint": "https://<cosmosdb-name>-westeurope.documents.azure.com:443/",
      "failoverPriority": 0,
      "id": "<cosmosdb-name>-westeurope",
      "locationName": "West Europe",
      "provisioningState": "Succeeded"
    }
  ]
} 

將 Node.js 應用程式連線到資料庫Connect your Node.js application to the database

在此步驟中,您會將 MEAN.js 範例應用程式連線至您剛才建立的 Cosmos 資料庫。In this step, you connect your MEAN.js sample application to Cosmos database you just created.

在 Node.js 應用程式中設定連接字串Configure the connection string in your Node.js application

在您的 MEAN.js 存放庫中,開啟 config/env/local-development.jsIn your MEAN.js repository, open config/env/local-development.js.

以下列程式碼取代此檔案的內容。Replace the content of this file with the following code. 務必也要使用您的 Cosmos 帳戶名稱來取代這兩個 <cosmosdb-name> 預留位置。Be sure to also replace the two <cosmosdb-name> placeholders with your Cosmos account name.

'use strict';

module.exports = {
  db: {
    uri: 'mongodb://<cosmosdb-name>:<primary_master_key>@<cosmosdb-name>.documents.azure.com:10255/mean-dev?ssl=true&sslverifycertificate=false'
  }
};

擷取金鑰Retrieve the key

若要連線至 Cosmos 資料庫,您需要資料庫金鑰。In order to connect to a Cosmos database, you need the database key. 使用 az cosmosdb keys list 命令來擷取主要金鑰。Use the az cosmosdb keys list command to retrieve the primary key.

az cosmosdb keys list --name <cosmosdb-name> --resource-group myResourceGroup --query "primaryMasterKey"

Azure CLI 會輸出類似下列範例的資訊。The Azure CLI outputs information similar to the following example.

"RUayjYjixJDWG5xTqIiXjC..."

複製 primaryMasterKey 的值。Copy the value of primaryMasterKey. 將此值貼到 local-development.js 中的 <primary_master_key> 上。Paste this over the <primary_master_key> in local-development.js.

儲存您的變更。Save your changes.

再次執行應用程式。Run the application again.

再次執行 npm startRun npm start again.

npm start

主控台訊息現在應告訴您開發環境已啟動並在執行中。A console message should now tell you that the development environment is up and running.

在瀏覽器中移至 http://localhost:3000Go to http://localhost:3000 in a browser. 選取上層功能表中的 [註冊] ,然後嘗試建立兩位虛擬使用者。Select Sign Up in the top menu and try to create two dummy users.

MEAN.js 範例應用程式會將使用者資料儲存於資料庫中。The MEAN.js sample application stores user data in the database. 如果您成功且 MEAN.js 自動登入至所建立的使用者,則您的 Cosmos DB 連線正在運作中。If you are successful and MEAN.js automatically signs into the created user, then your Azure Cosmos DB connection is working.

MEAN.js 成功連線至 MongoDB

在資料總管中檢視資料View data in Data Explorer

Cosmos 資料庫中儲存的資料可在 Azure 入口網站中進行檢視和查詢。Data stored in a Cosmos database is available to view and query in the Azure portal.

若要檢視、查詢及處理在前一個步驟中建立的使用者資料,請在 Web 瀏覽器中登入 Azure 入口網站To view, query, and work with the user data created in the previous step, login to the Azure portal in your web browser.

在頂端的 [搜尋] 方塊中,輸入 Azure Cosmos DBIn the top Search box, enter Azure Cosmos DB. 當您的 Cosmos 帳戶刀鋒視窗開啟時,選取您的 Cosmos 帳戶。When your Cosmos account blade opens, select your Cosmos account. 在左側導覽中,選取 [資料總管] 。In the left navigation, select Data Explorer. 在 [集合] 窗格中展開您的集合,然後您可以檢視集合中的文件、查詢資料,甚至是建立及執行預存程序、觸發程序和 UDF。Expand your collection in the Collections pane, and then you can view the documents in the collection, query the data, and even create and run stored procedures, triggers, and UDFs.

Azure 入口網站中的資料總管

將 Node.js 應用程式部署至 AzureDeploy the Node.js application to Azure

在此步驟中,您會將 Node.js 應用程式部署至 Cosmos DB。In this step, you deploy your Node.js application to Cosmos DB.

您可能已注意到,您稍早變更的組態檔適用於開發環境 (/config/env/local-development.js)。You may have noticed that the configuration file that you changed earlier is for the development environment (/config/env/local-development.js). 當您將應用程式部署至 App Service 時,它會依照預設在生產環境中執行。When you deploy your application to App Service, it will run in the production environment by default. 所以現在,您需要對個別的組態檔進行相同的變更。So now, you need to make the same change to the respective configuration file.

在您的 MEAN.js 存放庫中,開啟 config/env/production.jsIn your MEAN.js repository, open config/env/production.js.

db 物件中,取代 uri 的值,如下列範例中所示。In the db object, replace the value of uri as show in the following example. 請務必取代預留位置,如同之前一樣。Be sure to replace the placeholders as before.

'mongodb://<cosmosdb-name>:<primary_master_key>@<cosmosdb-name>.documents.azure.com:10255/mean?ssl=true&sslverifycertificate=false',

注意

ssl=true 選項很重要,因為 Cosmos DB 需要 SSLThe ssl=true option is important because Cosmos DB requires SSL.

在終端機中,將所有的變更認可至 Git。In the terminal, commit all your changes into Git. 您可以複製這兩個命令,以便同時執行它們。You can copy both commands to run them together.

git add .
git commit -m "configured MongoDB connection string"

清除資源Clean up resources

完成您的 Web 應用程式和 Azure Cosmos DB 帳戶之後,您可以將建立的 Azure 資源刪除,以免產生更多費用。When you're done with your web app and Azure Cosmos DB account, you can delete the Azure resources you created so you don't incur more charges. 若要刪除資源:To delete the resources:

  1. 在 Azure 入口網站中,選取最左邊的 [資源群組] 。In the Azure portal, select Resource groups on the far left. 若已摺疊左側功能表,請選取展開按鈕加以展開。If the left menu is collapsed, select Expand button to expand it.

  2. 選取您在本快速入門中建立的資源群組。Select the resource group you created for this quickstart.

    選取要刪除的資源群組

  3. 在新視窗中,選取 [刪除資源群組] 。In the new window, select Delete resource group.

    刪除資源群組

  4. 在下個視窗中輸入要刪除的資源群組名稱,然後選取 [刪除] 。In the next window, enter the name of the resource group to delete, and then select Delete.

後續步驟Next steps

在本快速入門中,您已了解如何建立 Cosmos 帳戶、建立集合,以及執行主控台應用程式。In this quickstart, you've learned how to create a Cosmos account, create a collection and run a console app. 您現在可以將其他資料匯入到 Cosmos 資料庫。You can now import additional data to your Cosmos database.