使用 Azure Cosmos DB 的用于 MongoDB 的 API 创建 Angular 应用 - 使用 Mongoose 连接到 Cosmos DBCreate an Angular app with Azure Cosmos DB's API for MongoDB - Use Mongoose to connect to Cosmos DB

本教程包含多个部分,演示了如何通过 Express 和 Angular 创建 Node.js 应用,然后将其连接到使用 Cosmos DB 的用于 MongoDB 的 API 配置的 Cosmos 帐户This multi-part tutorial demonstrates how to create a Node.js app with Express and Angular, and connect it to it to your Cosmos account configured with Cosmos DB's API for MongoDB. 本文是教程的第 5 部分,内容基于第 4 部分This article describes Part 5 of the tutorial and builds on Part 4.

本教程部分介绍以下操作:In this part of the tutorial, you will:

  • 使用 Mongoose 连接到 Cosmos DB。Use Mongoose to connect to Cosmos DB.
  • 获取 Cosmos DB 连接字符串。Get your Cosmos DB connection string.
  • 创建 Hero 模型。Create the Hero model.
  • 创建 Hero 服务用于获取 Hero 数据。Create the Hero service to get Hero data.
  • 在本地运行应用。Run the app locally.

如果没有 Azure 订阅,请在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.

先决条件Prerequisites

  • 开始本教程之前,请先完成第 4 部分中的步骤。Before you start this tutorial, complete the steps in Part 4.

  • 本教程要求在本地运行 Azure CLI。This tutorial requires that you run the Azure CLI locally. 必须安装 Azure CLI 2.0 或更高版本。You must have the Azure CLI version 2.0 or later installed. 运行 az --version 即可查找版本。Run az --version to find the version. 如果需要安装或升级 Azure CLI,请参阅安装 Azure CLI 2.0If you need to install or upgrade the Azure CLI, see Install the Azure CLI 2.0.

  • 本教程介绍生成应用程序的各个步骤。This tutorial walks you through the steps to build the application step by step. 若要下载完成的项目,可从 GitHub 上的 angular-cosmosdb 存储库获取完成的应用程序。If you want to download the finished project, you can get the completed application from the angular-cosmosdb repo on GitHub.

使用 Mongoose 进行连接Use Mongoose to connect

Mongoose 是适用于 MongoDB 和 Node.js 的对象数据建模 (ODM) 库。Mongoose is an object data modeling (ODM) library for MongoDB and Node.js. 可以使用 Mongoose 连接到 Azure Cosmos DB 帐户。You can use Mongoose to connect to your Azure Cosmos DB account. 使用以下步骤安装 Mongoose 并连接到 Azure Cosmos DB:Use the following steps to install Mongoose and connect to Azure Cosmos DB:

  1. 安装 Mongoose NPM 模块 - 用来与 MongoDB 通信的 API。Install the mongoose npm module, which is an API that's used to talk to MongoDB.

    npm i mongoose --save
    
  2. server 文件夹中,创建名为 mongo.js 的文件。In the server folder, create a file named mongo.js. 将 Azure Cosmos DB 帐户的连接详细信息添加到此文件。You'll add the connection details of your Azure Cosmos DB account to this file.

  3. 将以下代码复制到 mongo.js 文件中。Copy the following code into the mongo.js file. 该代码提供以下功能:The code provides the following functionality:

    • 需要 Mongoose。Requires Mongoose.

    • 替代 Mongo 约定,以使用 ES6/ES2015 和更高版本中内置的基本约定。Overrides the Mongo promise to use the basic promise that's built into ES6/ES2015 and later versions.

    • 根据是在过渡、生产还是开发环境中操作,针对 env 文件发出调用以设置某些项目。Calls on an env file that lets you set up certain things based on whether you're in staging, production, or development. 将在下一部分创建该文件。You'll create that file in the next section.

    • 请包含 env 文件中设置的 MongoDB 连接字符串。Includes the MongoDB connection string, which is set in the env file.

    • 创建调用 Mongoose 的 connect 函数。Creates a connect function that calls Mongoose.

      const mongoose = require('mongoose');
      /**
      * Set to Node.js native promises
      * Per https://mongoosejs.com/docs/promises.html
      */
      mongoose.Promise = global.Promise;
      
      const env = require('./env/environment');
      
      // eslint-disable-next-line max-len
      const mongoUri = `mongodb://${env.accountName}:${env.key}@${env.accountName}.documents.azure.cn:${env.port}/${env.databaseName}?ssl=true`;
      
      function connect() {
      mongoose.set('debug', true);
      return mongoose.connect(mongoUri, { useMongoClient: true });
      }
      
      module.exports = {
      connect,
      mongoose
      };
      
  4. 在“资源管理器”窗格中的“server”下,创建名为 environment 的文件夹。In the Explorer pane, under server, create a folder named environment. environment 文件夹中创建名为 environment.js 的文件。In the environment folder, create a file named environment.js.

  5. 在 mongo.js 文件中,需要包含 dbNamekeycosmosPort 参数的值。From the mongo.js file, we need to include values for the dbName, the key, and the cosmosPort parameters. 将以下代码复制到 environment.js 文件中:Copy the following code into the environment.js file:

    // TODO: replace if yours are different
    module.exports = {
      accountName: 'your-cosmosdb-account-name-goes-here',
      databaseName: 'admin', 
      key: 'your-key-goes-here',
      port: 10255
    };
    

获取连接字符串Get the connection string

若要将应用程序连接到 Azure Cosmos DB,需要更新应用程序的配置设置。To connect your application to Azure Cosmos DB, you need to update the configuration settings for the application. 使用以下步骤更新设置:Use the following steps to update the settings:

  1. 在 Azure 门户中,获取端口号、Azure Cosmos DB 帐户名,以及 Azure Cosmos DB 帐户的主密钥值。In the Azure portal, get the port number, Azure Cosmos DB account name, and primary key values for your Azure Cosmos DB account.

  2. environment.js 文件中,将 port 的值更改为 10255。In the environment.js file, change the value of port to 10255.

    const port = 10255;
    
  3. environment.js 文件中,将 accountName 的值更改为在本教程步骤 4 中创建的 Azure Cosmos DB 帐户的名称。In the environment.js file, change the value of accountName to the name of the Azure Cosmos DB account that you created in Part 4 of the tutorial.

  4. 在 Terminal 窗口中使用以下 CLI 命令,检索 Azure Cosmos DB 帐户的主密钥:Retrieve the primary key for the Azure Cosmos DB account by using the following CLI command in the terminal window:

    az cosmosdb list-keys --name <cosmosdb-name> -g myResourceGroup
    

    你在本教程第 4 部分中创建的 Azure Cosmos DB 帐户名为 <cosmosdb-name>。<cosmosdb-name> is the name of the Azure Cosmos DB account that you created in Part 4 of the tutorial.

  5. 将主密钥作为 key 值复制到“environment.js”文件中。Copy the primary key into the environment.js file as the key value.

现在,应用程序拥有了连接到 Azure Cosmos DB 所需的所有必要信息。Now your application has all the necessary information to connect to Azure Cosmos DB.

创建 Hero 模型Create a Hero model

接下来,你需要通过定义模型文件来定义要存储在 Azure Cosmos DB 中的数据的架构。Next, you need to define the schema of the data to store in Azure Cosmos DB by defining a model file. 使用以下步骤创建一个定义数据架构的 Hero 模型:Use the following steps to create a Hero model that defines the schema of the data:

  1. 在“资源管理器”窗格的“服务器”文件夹下,创建一个名为“hero.model.js”的文件。In the Explorer pane, under the server folder, create a file named hero.model.js.

  2. 将以下代码复制到“hero.model.js”文件中。Copy the following code into the hero.model.js file. 此代码提供以下功能:The code provides the following functionality:

    • 需要 Mongoose。Requires Mongoose.
    • 使用 ID、name 和 saying 创建新架构。Creates a new schema with an ID, name, and saying.
    • 通过使用该架构创建模型。Creates a model by using the schema.
    • 导出模型。Exports the model.
    • 将集合命名为“Heroes”而不是“Heros”(根据 Mongoose 复数形式命名规则,后者为集合的默认名称)。Names the collection Heroes (instead of Heros, which is the default name of the collection based on Mongoose plural naming rules).
    const mongoose = require('mongoose');
    
    const Schema = mongoose.Schema;
    
    const heroSchema = new Schema(
      {
        id: { type: Number, required: true, unique: true },
        name: String,
        saying: String
      },
      {
        collection: 'Heroes'
      }
    );
    
    const Hero = mongoose.model('Hero', heroSchema);
    
    module.exports = Hero;
    

创建 Hero 服务Create a Hero service

创建 Hero 模型后,需要定义一个服务用于读取数据,以及执行 list、create、delete 和 update 操作。After you create the hero model, you need to define a service to read the data, and perform list, create, delete, and update operations. 使用以下步骤创建一个 Hero 服务用于查询 Azure Cosmos DB 中的数据:Use the following steps to create a Hero service that queries the data from Azure Cosmos DB:

  1. 在“资源管理器”窗格中的“server”文件夹下,创建名为 hero.service.js 的文件。In the Explorer pane, under the server folder, create a file named hero.service.js.

  2. 将以下代码复制到 hero.service.js 文件中。Copy the following code into the hero.service.js file. 该代码提供以下功能:The code provides the following functionality:

    • 获取创建的模型。Gets the model that you created.
    • 连接到数据库。Connects to the database.
    • 创建 docquery 变量,以便使用 hero.find 方法定义一个返回所有 Hero 的查询。Creates a docquery variable that uses the hero.find method to define a query that returns all heroes.
    • 结合 docquery.exec 函数运行查询。该函数中的约定可以获取响应状态为 200 的所有 Hero 的列表。Runs a query with the docquery.exec function with a promise to get a list of all heroes, where the response status is 200.
    • 如果状态为 500,则发回错误消息。Sends back the error message if the status is 500.
    • 由于使用的是模块,因此可以获取 Hero。Gets the heroes because we're using modules.
    const Hero = require('./hero.model');
    
    require('./mongo').connect();
    
    function getHeroes() {
      const docquery = Hero.find({});
      docquery
        .exec()
        .then(heroes => {
          res.status(200).json(heroes);
        })
        .catch(error => {
          res.status(500).send(error);
          return;
        });
    }
    
    module.exports = {
      getHeroes
    };
    

配置路由Configure routes

接下来,需要设置路由用于处理 get、create、read 和 delete 请求的 URL。Next, you need to set up routes to handle the URLs for get, create, read, and delete requests. 路由方法指定回调函数(也称为“处理程序函数”)。The routing methods specify callback functions (also called handler functions). 当应用程序接收到发往指定终结点和 HTTP 方法的请求时,会调用这些函数。These functions are called when the application receives a request to the specified endpoint and HTTP method. 使用以下步骤添加 Hero 服务并定义路由:Use the following steps to add the Hero service and to define your routes:

  1. 在 Visual Studio Code 中的 routes.js 文件内,注释掉发送示例 Hero 数据的 res.send 函数。In Visual Studio Code, in the routes.js file, comment out the res.send function that sends the sample hero data. 添加一行代码,以改为调用 heroService.getHeroes 函数。Add a line to call the heroService.getHeroes function instead.

    router.get('/heroes', (req, res) => {
      heroService.getHeroes(req, res);
    //  res.send(200, [
    //      {"id": 10, "name": "Starlord", "saying": "oh yeah"}
    //  ])
    });
    
  2. routes.js 文件中,为 Hero 服务添加 require 语句:In the routes.js file, require the hero service:

    const heroService = require('./hero.service'); 
    
  3. hero.service.js 文件中更新 getHeroes 函数,以采用 reqres 参数,如下所示:In the hero.service.js file, update the getHeroes function to take the req and res parameters as follows:

    function getHeroes(req, res) {
    

请花点时间查看并演练上面的代码。Let's take a minute to review and walk through the previous code. 首先查看 index.js 文件,此文件用于设置节点服务器。First, we come into the index.js file, which sets up the node server. 可以看到,其中设置并定义了路由。Notice that it sets up and defines your routes. 接下来,routes.js 文件与 Hero 服务通信,要求该服务获取 getHeroes 之类的函数,并传递请求和响应。Next, your routes.js file talks to the hero service and tells it to get your functions, like getHeroes, and pass the request and response. hero.service.js 文件获取模型并连接到 Mongo。The hero.service.js file gets the model and connects to Mongo. 然后,此文件执行调用的 getHeroes,并返回响应 200。Then it executes getHeroes when we call it, and returns back a response of 200.

运行应用程序Run the app

接下来,请使用以下步骤运行应用:Next, run the app by using the following steps:

  1. 在 Visual Studio Code 中保存所有更改。In Visual Studio Code, save all your changes. 在左侧选择“调试”按钮 Visual Studio Code 中的“调试”图标,然后选择“开始调试”按钮 Visual Studio Code 中的“调试”图标On the left, select the Debug button Debug icon in Visual Studio Code, and then select the Start Debugging button Debug icon in Visual Studio Code.

  2. 现在切换到浏览器。Now switch to the browser. 打开“开发人员工具”和“网络”选项卡。转到 http://localhost:3000,其中显示了我们的应用程序。Open the Developer tools and the Network tab. Go to http://localhost:3000, and there you see our application.

    Azure 门户中的新 Azure Cosmos DB 帐户

尚无 Hero 存储在该应用中。There are no heroes stored yet in the app. 在本教程的下一部分,我们将添加放置、推送和删除功能。In the next part of this tutorial, we'll add put, push, and delete functionality. 然后,我们便可以使用与 Azure Cosmos DB 数据库建立的 Mongoose 连接,在 UI 中添加、更新和删除 Hero。Then we can add, update, and delete heroes from the UI by using Mongoose connections to our Azure Cosmos DB database.

清理资源Clean up resources

不再需要本教程中创建的资源时,可以删除相应的资源组、Azure Cosmos DB 帐户和所有相关资源。When you no longer need the resources, you can delete the resource group, Azure Cosmos DB account, and all the related resources. 使用以下步骤删除资源组:Use the following steps to delete the resource group:

  1. 转到在其中创建了 Azure Cosmos DB 帐户的资源组。Go to the resource group where you created the Azure Cosmos DB account.
  2. 选择“删除资源组”。Select Delete resource group.
  3. 确认要删除的资源组的名称,然后选择“删除”。Confirm the name of the resource group to delete, and select Delete.

后续步骤Next steps

请转到本教程的第 6 部分,了解如何向应用添加 Post、Put 和 Delete 函数:Continue to Part 6 of the tutorial to add Post, Put, and Delete functions to the app: