快速入门:将现有的 MongoDB Node.js Web 应用迁移到 Azure Cosmos DBQuickstart: Migrate an existing MongoDB Node.js web app to Azure Cosmos DB

在本快速入门中,你将使用 Azure 本地 Shell 以及从 GitHub 克隆的 MEAN(MongoDB、Express、Angular 和 Node.js)应用来创建和管理 Azure Cosmos DB for Mongo DB API 帐户。In this quickstart, you create and manage an Azure Cosmos DB for Mongo DB API account by using the Azure local Shell, and with a MEAN (MongoDB, Express, Angular, and Node.js) app cloned from GitHub. Azure Cosmos DB 是一种多模型数据库服务,可让你通过多区域分布和水平缩放功能快速创建和查询文档、表、键/值和图数据库。Azure Cosmos DB is a multi-model database service that lets you quickly create and query document, table, key-value, and graph databases with multiple-region distribution and horizontal scale capabilities.

先决条件Prerequisites

  • 具有活动订阅的 Azure 帐户。An Azure account with an active subscription. 免费创建一个Create one for free. 你还可以将 Azure Cosmos DB 模拟器与连接字符串 .mongodb://localhost:C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==@localhost:10255/admin?ssl=true 配合使用。You can also use the Azure Cosmos DB Emulator with the connection string .mongodb://localhost:C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==@localhost:10255/admin?ssl=true.

  • Node.js,应具备 Node.js 的实践知识。Node.js, and a working knowledge of Node.js.

  • GitGit.

  • Azure CLI 2.0+Azure CLI 2.0+.

备注

在 Azure China 中使用 Azure CLI 2.0 之前,请首先运行 az cloud set -n AzureChinaCloud 更改云环境。Before you can use Azure CLI 2.0 in Azure China, please run az cloud set -n AzureChinaCloud first to change the cloud environment. 如果要切换回全局 Azure,请再次运行 az cloud set -n AzureCloudIf you want to switch back to Global Azure, run az cloud set -n AzureCloud again.

克隆示例应用程序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

此 MongoDB 应用程序以 node.js 编写,连接到支持 MongoDB 客户端的 Azure Cosmos DB 数据库。This MongoDB app written in Node.js connects to your Azure Cosmos DB database, which supports MongoDB client. 换言之,应用程序完全知道数据存储在 Azure Cosmos DB 数据库中。In other words, it is transparent to the application that the data is stored in an Azure Cosmos DB database.

安装所需的包,并启动应用程序。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]".

登录 AzureSign in to Azure

如果选择在本地安装并使用 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 CLI,请使用 az login 命令登录到 Azure 订阅,然后按屏幕说明操作。When you are using an installed Azure CLI, sign in to your Azure subscription with the az login command and follow the on-screen directions.

备注

在 Azure China 中使用 Azure CLI 2.0 之前,请首先运行 az cloud set -n AzureChinaCloud 更改云环境。Before you can use Azure CLI 2.0 in Azure China, please run az cloud set -n AzureChinaCloud first to change the cloud environment. 如果要切换回全局 Azure,请再次运行 az cloud set -n AzureCloudIf you want to switch back to Global Azure, run az cloud set -n AzureCloud again.

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.

如果 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 China North region. 选择资源组的唯一名称。Choose a unique name for the resource group.

az group create --name myResourceGroup --location "China North"

创建 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.cn/) 的一部分,因此这个名称需要在 Azure 中的所有 Cosmos 帐户中具有唯一性。This unique name will be used as part of your Cosmos DB endpoint (https://<cosmosdb-name>.documents.azure.cn/), 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.cn:443/",
  "id": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Document
DB/databaseAccounts/<cosmosdb-name>",
  "kind": "MongoDB",
  "location": "China North",
  "name": "<cosmosdb-name>",
  "readLocations": [
    {
      "documentEndpoint": "https://<cosmosdb-name>-chinanorth.documents.azure.cn:443/",
      "failoverPriority": 0,
      "id": "<cosmosdb-name>-chinanorth",
      "locationName": "China North",
      "provisioningState": "Succeeded"
    }
  ],
  "resourceGroup": "myResourceGroup",
  "type": "Microsoft.DocumentDB/databaseAccounts",
  "writeLocations": [
    {
      "documentEndpoint": "https://<cosmosdb-name>-chinanorth.documents.azure.cn:443/",
      "failoverPriority": 0,
      "id": "<cosmosdb-name>-chinanorth",
      "locationName": "China North",
      "provisioningState": "Succeeded"
    }
  ]
} 

将 Node.js 应用程序连接至数据库Connect your Node.js application to the database

在此步骤中,将 MEAN.js 示例应用程序连接到你刚才创建的 Azure Cosmos DB 数据库帐户。In this step, you connect your MEAN.js sample application to the Azure Cosmos DB database account 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.cn: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.

MEAN.js 成功连接至 MongoDB

将 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.cn:10255/mean?ssl=true&sslverifycertificate=false',

备注

由于 Cosmos DB 的要求,ssl=true 选项很重要。The ssl=true option is important because of Cosmos DB requirements. 有关详细信息,请参阅连接字符串要求For more information, see Connection string requirements.

在终端中,将所有更改提交到 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

执行完应用和 Azure Cosmos DB 帐户的操作以后,可以删除所创建的 Azure 资源,以免产生更多费用。When you're done with your 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 Search bar, search for and select Resource groups.

  2. 从列表中选择为本快速入门创建的资源组。From the list, select the resource group you created for this quickstart.

    选择要删除的资源组

  3. 在资源组“概览”页上,选择“删除资源组” 。On the resource group Overview page, select Delete resource group.

    删除资源组

  4. 在下一窗口中输入要删除的资源组的名称,然后选择“删除” 。In the next window, enter the name of the resource group to delete, and then select Delete.

后续步骤Next steps

本快速入门介绍了如何使用 Azure 本地 Shell 创建 Azure Cosmos DB MongoDB API 帐户,以及如何创建和运行 MEAN.js 应用以将用户添加到该帐户。In this quickstart, you learned how to create an Azure Cosmos DB MongoDB API account using the Azure local Shell, and create and run a MEAN.js app to add users to the account. 现在可以将其他数据导入 Azure Cosmos DB 帐户了。You can now import additional data to your Azure Cosmos DB account.