您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

快速入门:将现有的 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.

完成本教程后,Cosmos DB 中会运行一个 MEAN(MongoDB、Express、Angular 和 Node.js)应用程序。When you are done, you will have a MEAN application (MongoDB, Express, Angular, and Node.js) running on Cosmos DB.

在 Azure 应用服务中运行的 MEAN.js 应用

使用 Azure Cloud ShellUse Azure Cloud Shell

Azure 托管 Azure Cloud Shell(一个可通过浏览器使用的交互式 shell 环境)。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 将代码粘贴到 Cloud Shell 会话中,或在 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 订阅即可免费试用 Azure Cosmos DB,也无需缴纳费用或承诺金。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 bash 之类的 git 终端窗口,并使用 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: 连接 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,请运行 az 命令,检查是否已安装 cosmosdb 组件。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. 另外,请务必将两个 <cosmosdb-name> 占位符替换为 Cosmos 帐户名。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 可自动登录到已创建的用户,则表示 Azure 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). 将应用程序部署到应用服务后,该应用程序默认在生产环境中运行。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.