教程:使用 JavaScript SDK 生成 Node.js 控制台应用以管理 Azure Cosmos DB SQL API 数据Tutorial: Build a Node.js console app with the JavaScript SDK to manage Azure Cosmos DB SQL API data

作为开发人员,你可能有使用 NoSQL 文件数据的应用程序。As a developer, you might have applications that use NoSQL document data. 可以使用 Azure Cosmos DB 中的 SQL API 帐户存储和访问此文档数据。You can use a SQL API account in Azure Cosmos DB to store and access this document data. 本教程介绍如何生成 Node.js 控制台应用程序,以便创建 Azure Cosmos DB 资源并对其进行查询。This tutorial shows you how to build a Node.js console application to create Azure Cosmos DB resources and query them.

在本教程中,将:In this tutorial, you will:

  • 创建并连接到 Azure Cosmos DB 帐户。Create and connect to an Azure Cosmos DB account.
  • 设置应用程序。Set up your application.
  • 创建数据库。Create a database.
  • 创建容器。Create a container.
  • 向容器添加项。Add items to the container.
  • 对项、容器和数据库执行基本操作。Perform basic operations on the items, container, and database.

先决条件Prerequisites

请确保具有以下资源:Make sure you have the following resources:

创建 Azure Cosmos DB 帐户Create Azure Cosmos DB account

让我们创建一个 Azure Cosmos DB 帐户。Let's create an Azure Cosmos DB account. 如果已经有想要使用的帐户,可以跳到 安装 Node.js 应用程序If you already have an account you want to use, you can skip ahead to Set up your Node.js application. 如果使用 Azure Cosmos DB 模拟器,请遵循 Azure Cosmos DB 模拟器中的步骤设置该模拟器,并直接跳到设置 Node.js 应用程序If you are using the Azure Cosmos DB Emulator, follow the steps at Azure Cosmos DB Emulator to set up the emulator and skip ahead to Set up your Node.js application.

  1. 在 Azure 门户菜单或主页中,选择“创建资源” 。From the Azure portal menu or the Home page, select Create a resource.

  2. 在“新建”页面中搜索“Azure Cosmos DB”,然后选择它。 On the New page, search for and select Azure Cosmos DB.

  3. 在“Azure Cosmos DB”页上,选择“创建”。On the Azure Cosmos DB page, select Create.

  4. 在“创建 Azure Cosmos DB 帐户”页上,输入新 Azure Cosmos 帐户的基本设置。On the Create Azure Cosmos DB Account page, enter the basic settings for the new Azure Cosmos account.

    设置Setting Value 说明Description
    订阅Subscription 订阅名称Subscription name 选择要用于此 Azure Cosmos 帐户的 Azure 订阅。Select the Azure subscription that you want to use for this Azure Cosmos account.
    资源组Resource Group 资源组名称Resource group name 选择一个资源组,或者选择“新建”,然后输入新资源组的唯一名称。Select a resource group, or select Create new, then enter a unique name for the new resource group.
    帐户名Account Name 唯一的名称A unique name 输入标识此 Azure Cosmos 帐户的名称。Enter a name to identify your Azure Cosmos account. 由于 documents.azure.cn 将追加到所提供的名称以创建 URI,因此,请使用唯一的名称**。Because documents.azure.cn is appended to the name that you provide to create your URI, use a unique name.

    名称只能包含小写字母、数字和连字符 (-)。The name can only contain lowercase letters, numbers, and the hyphen (-) character. 它的长度必须介于 3-44 个字符之间。It must be between 3-44 characters in length.
    APIAPI 要创建的帐户的类型The type of account to create 选择“Core (SQL)”,以便使用 SQL 语法创建文档数据库并进行查询。Select Core (SQL) to create a document database and query by using SQL syntax.

    API 确定要创建的帐户的类型。The API determines the type of account to create. Azure Cosmos DB 提供五种 API:适用于文档数据的 Core (SQL) 和 MongoDB、适用于图形数据的 Gremlin、Azure 表和 Cassandra。Azure Cosmos DB provides five APIs: Core (SQL) and MongoDB for document data, Gremlin for graph data, Azure Table, and Cassandra. 目前,你必须为每种 API 创建单独的帐户。Currently, you must create a separate account for each API.
    应用免费层折扣Apply Free Tier Discount 应用或不应用Apply or Do not apply 使用 Azure Cosmos DB 免费层,你将在帐户中获得每秒的前 400 RU 免费的吞吐量和 5 GB 的免费存储。With Azure Cosmos DB free tier, you will get the first 400 RU/s and 5 GB of storage for free in an account. 了解免费层的详细信息。Learn more about free tier.
    位置Location 离用户最近的区域The region closest to your users 选择用于托管 Azure Cosmos DB 帐户的地理位置。Select a geographic location to host your Azure Cosmos DB account. 使用离用户最近的位置,使他们能够以最快的速度访问数据。Use the location that is closest to your users to give them the fastest access to the data.
    帐户类型Account Type 生产或非生产Production or Non-Production 如果帐户将用于生产工作负荷,请选择“生产”。Select Production if the account will be used for a production workload. 如果帐户将用于非生产环境(例如开发、测试、QA 或过渡),请选择“非生产”。Select Non-Production if the account will be used for non-production, e.g. development, testing, QA, or staging. 这是一个 Azure 资源标记设置,用于调整门户体验,但不会影响基础 Azure Cosmos DB 帐户。This is an Azure resource tag setting that tunes the Portal experience but does not affect the underlying Azure Cosmos DB account. 可以随时更改此值。You can change this value anytime.

    备注

    每个 Azure 订阅最多可以有一个免费层 Azure Cosmos DB 帐户,并且你必须在创建帐户时选择加入使用。You can have up to one free tier Azure Cosmos DB account per Azure subscription and must opt-in when creating the account. 如果看不到用于应用免费层折扣的选项,这意味着订阅中的另一个帐户已启用免费层。If you do not see the option to apply the free tier discount, this means another account in the subscription has already been enabled with free tier.

    Azure Cosmos DB 的“新建帐户”页面

  5. 选择“查看 + 创建”。Select Review + create. 可以跳过“网络”和“标记”部分 。You can skip the Network and Tags sections.

  6. 检查帐户设置,然后选择“创建”。Review the account settings, and then select Create. 创建帐户需要几分钟时间。It takes a few minutes to create the account. 等待门户页显示“你的部署已完成”消息。Wait for the portal page to display Your deployment is complete.

    Azure 门户“通知”窗格

  7. 选择“转到资源”,转到 Azure Cosmos DB 帐户页。Select Go to resource to go to the Azure Cosmos DB account page.

    Azure Cosmos DB 帐户页面

设置 Node.js 应用程序Set up your Node.js application

在开始编写生成应用程序所需的代码之前,可以生成应用的框架。Before you start writing code to build the application, you can build the framework for your app. 运行以下步骤,设置包含框架代码的 Node.js 应用程序:Run the following steps to set up your Node.js application that has the framework code:

  1. 打开最喜爱的终端。Open your favorite terminal.

  2. 找到想要在其中保存 Node.js 应用程序的文件夹或目录。Locate the folder or directory where you'd like to save your Node.js application.

  3. 使用以下命令创建空的 JavaScript 文件:Create empty JavaScript files with the following commands:

    • Windows:Windows:

      • fsutil file createnew app.js 0
      • fsutil file createnew config.js 0
      • md data
      • fsutil file createnew data\databaseContext.js 0
    • Linux/OS X:Linux/OS X:

      • touch app.js
      • touch config.js
      • mkdir data
      • touch data/databaseContext.js
  4. 创建并初始化 package.json 文件。Create and initialize a package.json file. 使用以下命令:Use the following command:

    • npm init -y
  5. 通过 npm 安装 @azure/cosmos 模块。Install the @azure/cosmos module via npm. 使用以下命令:Use the following command:

    • npm install @azure/cosmos --save

设置应用的配置Set your app's configurations

有了应用以后,需确保它可以与 Azure Cosmos DB 通信。Now that your app exists, you need to make sure it can talk to Azure Cosmos DB. 如以下步骤所示,更新一些配置设置即可将应用设置为与 Azure Cosmos DB 通信:By updating a few configuration settings, as shown in the following steps, you can set your app to talk to Azure Cosmos DB:

  1. 在你喜欢使用的文本编辑器中打开 config.js 文件。Open the config.js file in your favorite text editor.

  2. 将以下代码片段复制并粘贴到 config.js 文件中,并将属性 endpointkey 设置为 Azure Cosmos DB 终结点 URI 和主密钥。Copy and paste the following code snippet into the config.js file and set the properties endpoint and key to your Azure Cosmos DB endpoint URI and primary key. 数据库和容器名称设置为“Tasks”和“Items”。 The database, container names are set to Tasks and Items. 将用于此应用程序的分区键是 /category。The partition key you will use for this application is /category.

    // @ts-check
    
    const config = {
        endpoint: "<Your Azure Cosmos account URI>",
        key: "<Your Azure Cosmos account key>",
        databaseId: "Tasks",
        containerId: "Items",
        partitionKey: { kind: "Hash", paths: ["/category"] }
    };
    
    module.exports = config;
    

    可在 Azure 门户的“键”窗格中找到终结点和键详细信息。You can find the endpoint and key details in the Keys pane of the Azure portal.

    从 Azure 门户获取密钥的屏幕截图

JavaScript SDK 使用通用术语“容器”和“项”。 The JavaScript SDK uses the generic terms container and item. 容器可以是集合、图或表。A container can be a collection, graph, or table. 项可以是文档、边缘/顶点或行,是容器中的内容。An item can be a document, edge/vertex, or row, and is the content inside a container. 在前面的代码片段中,module.exports = config; 代码用于导出 config 对象,以便你在 app.js 文件中引用它。In the previous code snippet, the module.exports = config; code is used to export the config object, so that you can reference it within the app.js file.

创建数据库和容器Create a database and a container

  1. 在你喜欢使用的文本编辑器中打开 databaseContext.js 文件。Open the databaseContext.js file in your favorite text editor.

  2. 将以下代码复制并粘贴到 databaseContext.js 文件中。Copy and paste the following code to the databaseContext.js file. 此代码定义了一个函数,该函数创建“Tasks”数据库和“Items”容器(如果它们在 Azure Cosmos 帐户中不存在):This code defines a function that creates the "Tasks", "Items" database and the container if they don't already exist in your Azure Cosmos account:

    const config = require("../config");
    const CosmosClient = require("@azure/cosmos").CosmosClient;
    
    /*
    // This script ensures that the database is setup and populated correctly
    */
    async function create(client, databaseId, containerId) {
        const partitionKey = config.partitionKey;
    
        /**
        * Create the database if it does not exist
        */
        const { database } = await client.databases.createIfNotExists({
            id: databaseId
        });
        console.log(`Created database:\n${database.id}\n`);
    
        /**
         * Create the container if it does not exist
         */
        const { container } = await client
            .database(databaseId)
            .containers.createIfNotExists(
            { id: containerId, partitionKey },
            { offerThroughput: 400 }
        );
    
        console.log(`Created container:\n${container.id}\n`);
    }
    
    module.exports = { create };
    
    

    数据库是跨容器分区的项的逻辑容器。A database is the logical container of items partitioned across containers. 使用 Databases 类的 createIfNotExists 或 create 函数创建数据库。You create a database by using either the createIfNotExists or create function of the Databases class. 在使用 SQL API 的情况下,包含项的容器为 JSON 文档。A container consists of items which in the case of the SQL API is JSON documents. 使用 Containers 类的 createIfNotExists 或 create 函数创建容器。You create a container by using either the createIfNotExists or create function from the Containers class. 创建容器后,你可以存储并查询数据。After creating a container, you can store and query the data.

    警告

    创建容器涉及到定价。Creating a container has pricing implications. 请访问定价页,了解相关信息。Visit our pricing page so you know what to expect.

导入配置Import the configuration

  1. 在你喜欢使用的文本编辑器中打开 app.js 文件。Open the app.js file in your favorite text editor.

  2. 复制并粘贴以下代码,以便导入在前面的步骤中定义的 @azure/cosmos 模块、配置和 databaseContext。Copy and paste the code below to import the @azure/cosmos module, the configuration, and the databaseContext that you defined in the previous steps.

    const CosmosClient = require("@azure/cosmos").CosmosClient;
    const config = require("./config");
    const dbContext = require("./data/databaseContext");
    

连接到 Azure Cosmos 帐户Connect to the Azure Cosmos account

在 app.js 文件中,复制并粘贴以下代码,以便使用前面保存的终结点和键来创建新的 CosmosClient 对象。In the app.js file, copy and paste the following code to use the previously saved endpoint and key to create a new CosmosClient object.

const { endpoint, key, databaseId, containerId } = config;

const client = new CosmosClient({ endpoint, key });

const database = client.database(databaseId);
const container = database.container(containerId);

// Make sure Tasks database is already setup. If not, create it.
await dbContext.create(client, databaseId, containerId);

备注

如果连接到 Cosmos DB 模拟器,请为节点进程禁用 TLS 验证:If connecting to the Cosmos DB Emulator, disable TLS verification for your node process:

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
const client = new CosmosClient({ endpoint, key });

现已获得用于初始化 Azure Cosmos DB 客户端的代码,接下来请看如何使用 Azure Cosmos DB 资源。Now that you have the code to initialize the Azure Cosmos DB client, let's take a look at how to work with Azure Cosmos DB resources.

查询项Query items

Azure Cosmos DB 支持对存储在每个容器中的 JSON 项进行各种查询。Azure Cosmos DB supports rich queries against JSON items stored in each container. 以下示例代码展示了一个可以针对容器中项运行的查询。可以使用 Items 类的 query 函数来查询项。The following sample code shows a query that you can run against the items in your container.You can query the items by using the query function of the Items class. 将以下代码添加到 app.js 文件中,以便从 Azure Cosmos 帐户查询项:Add the following code to the app.js file to query the items from your Azure Cosmos account:

console.log(`Querying container: Items`);

// query to return all items
const querySpec = {
  query: "SELECT * from c"
};

// read all items in the Items container
const { resources: items } = await container.items
  .query(querySpec)
  .fetchAll();

items.forEach(item => {
  console.log(`${item.id} - ${item.description}`);
});

创建项Create an item

可以使用 Items 类的 create 函数创建项。An item can be created by using the create function of the Items class. 使用 SQL API 时,项会投射为文档,后者是用户定义的(任意)JSON 内容。When you're using the SQL API, items are projected as documents, which are user-defined (arbitrary) JSON content. 在本教程中,我们在 tasks 数据库中创建一个新项。In this tutorial, you create a new item within the tasks database.

  1. 在 app.js 文件中,定义项定义:In the app.js file, define the item definition:

    const newItem = {
      id: "3",
      category: "fun",
      name: "Cosmos DB",
      description: "Complete Cosmos DB Node.js Quickstart ⚡",
      isComplete: false
    };
    
  2. 添加以下代码,以便创建前面定义的项:Add the following code to create the previously defined item:

    /** Create new item
    * newItem is defined at the top of this file
    */
    const { resource: createdItem } = await container.items.create(newItem);
    
    console.log(`\r\nCreated new item: ${createdItem.id} - ${createdItem.description}\r\n`);
    
    

更新项Update an item

Azure Cosmos DB 支持替换项的内容。Azure Cosmos DB supports replacing the contents of items. 将以下代码复制并粘贴到 app.js 文件中。Copy and paste the following code to app.js file. 此代码获取容器中的某个项,并将 isComplete 字段更新为 true。This code gets an item from the container and updates the isComplete field to true.

/** Update item
 * Pull the id and partition key value from the newly created item.
 * Update the isComplete field to true.
 */
const { id, category } = createdItem;

createdItem.isComplete = true;

const { resource: updatedItem } = await container
  .item(id, category)
  .replace(createdItem);

console.log(`Updated item: ${updatedItem.id} - ${updatedItem.description}`); 
console.log(`Updated isComplete to ${updatedItem.isComplete}\r\n`);

删除项Delete an item

Azure Cosmos DB 支持删除 JSON 项。Azure Cosmos DB supports deleting JSON items. 以下代码展示了如何通过项 ID 获取项并将其删除。The following code shows how to get an item by its ID and delete it. 将以下代码复制并粘贴到 app.js 文件中:Copy and paste the following code to app.js file:

/**
 * Delete item
 * Pass the id and partition key value to delete the item
 */
const { resource: result } = await container.item(id, category).delete();
console.log(`Deleted item with id: ${id}`);

运行 Node.js 应用程序Run your Node.js application

总起来看,代码应如下所示:Altogether, your code should look like this:

// @ts-check
//  <ImportConfiguration>
const CosmosClient = require("@azure/cosmos").CosmosClient;
const config = require("./config");
const dbContext = require("./data/databaseContext");
//  </ImportConfiguration>

//  <DefineNewItem>
const newItem = {
  id: "3",
  category: "fun",
  name: "Cosmos DB",
  description: "Complete Cosmos DB Node.js Quickstart ⚡",
  isComplete: false
};
//  </DefineNewItem>

async function main() {

  // <CreateClientObjectDatabaseContainer>
  const { endpoint, key, databaseId, containerId } = config;

  const client = new CosmosClient({ endpoint, key });

  const database = client.database(databaseId);
  const container = database.container(containerId);

  // Make sure Tasks database is already setup. If not, create it.
  await dbContext.create(client, databaseId, containerId);
  // </CreateClientObjectDatabaseContainer>

  try {
    // <QueryItems>
    console.log(`Querying container: Items`);

    // query to return all items
    const querySpec = {
      query: "SELECT * from c"
    };

    // read all items in the Items container
    const { resources: items } = await container.items
      .query(querySpec)
      .fetchAll();

    items.forEach(item => {
      console.log(`${item.id} - ${item.description}`);
    });
    // </QueryItems>

    // <CreateItem>
    /** Create new item
     * newItem is defined at the top of this file
     */
    const { resource: createdItem } = await container.items.create(newItem);

    console.log(`\r\nCreated new item: ${createdItem.id} - ${createdItem.description}\r\n`);
    // </CreateItem>

    // <UpdateItem>
    /** Update item
     * Pull the id and partition key value from the newly created item.
     * Update the isComplete field to true.
     */
    const { id, category } = createdItem;

    createdItem.isComplete = true;

    const { resource: updatedItem } = await container
      .item(id, category)
      .replace(createdItem);

    console.log(`Updated item: ${updatedItem.id} - ${updatedItem.description}`); 
    console.log(`Updated isComplete to ${updatedItem.isComplete}\r\n`);
    // </UpdateItem>

    // <DeleteItem>    
    /**
     * Delete item
     * Pass the id and partition key value to delete the item
     */
    const { resource: result } = await container.item(id, category).delete();
    console.log(`Deleted item with id: ${id}`);
    // </DeleteItem>  

  } catch (err) {
    console.log(err.message);
  }
}

main();

在终端中,找到 app.js 文件并运行以下命令:In your terminal, locate your app.js file and run the command:

node app.js

应该看到已启动应用的输出。You should see the output of your get started app. 输出应该匹配下面的示例文本。The output should match the example text below.

Created database:
Tasks

Created container:
Items

Querying container: Items
1 - Pick up apples and strawberries.

Created new item: 3 - Complete Cosmos DB Node.js Quickstart ⚡

Updated item: 3 - Complete Cosmos DB Node.js Quickstart ⚡
Updated isComplete to true

Deleted item with id: 3

获取完整的 Node.js 教程解决方案Get the complete Node.js tutorial solution

如果没有时间完成本教程中的步骤,或者只需下载代码,则可从 GitHub 获取。If you didn't have time to complete the steps in this tutorial, or just want to download the code, you can get it from GitHub.

若要运行包含本文所有代码的入门解决方案,需要以下项:To run the getting started solution that contains all the code in this article, you will need:

通过 npm 安装项目的依赖项。Install the project's dependencies via npm. 使用以下命令:Use the following command:

  • npm install

接下来,在 config.js 文件中更新 config.endpoint 和 config.key 的值,如步骤 3:设置应用的配置中所述。Next, in the config.js file, update the config.endpoint and config.key values as described in Step 3: Set your app's configurations.

然后在终端中找到 app.js 文件并运行以下命令:Then in your terminal, locate your app.js file and run the command:

node app.js 

清理资源Clean up resources

不再需要资源组、Azure Cosmos DB 帐户和所有相关的资源时,可将这些资源删除。When these resources are no longer needed, you can delete the resource group, Azure Cosmos DB account, and all the related resources. 为此,请选择用于 Azure Cosmos DB 帐户的资源组,接着选择“删除”,然后确认要删除的资源组的名称。To do so, select the resource group that you used for the Azure Cosmos DB account, select Delete, and then confirm the name of the resource group to delete.

后续步骤Next steps