65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 JavaScript SDK 构建 Node.js 控制台应用程序来管理 Azure Cosmos DB SQL API 数据

starIconstarIconemptyStarIconemptyStarIconemptyStarIcon

2.00/5 (1投票)

2018年12月21日

CPOL
viewsIcon

9865

本教程向您展示如何构建一个 Node.js 控制台应用程序,以创建 Azure Cosmos DB 资源并查询它们。

作为开发人员,您可能拥有使用 NoSQL 文档数据的应用程序。您可以使用 Azure Cosmos DB 中的 SQL API 帐户来存储和访问此文档数据。本教程向您展示如何构建一个 Node.js 控制台应用程序,以创建 Azure Cosmos DB 资源并查询它们。

在本教程中,您将:

  • 创建并连接到 Azure Cosmos DB 帐户。
  • 设置您的应用程序。
  • 创建一个数据库。
  • 创建一个容器。
  • 向容器添加项目。
  • 对项目、容器和数据库执行基本操作。

必备组件

确保您拥有以下资源:

创建 Azure Cosmos DB 帐户

让我们创建一个 Azure Cosmos DB 帐户。如果您已经有要使用的帐户,可以跳到设置您的 Node.js 应用程序。如果您正在使用 Azure Cosmos DB 模拟器,请按照Azure Cosmos DB 模拟器中的步骤设置模拟器,然后跳到设置您的 Node.js 应用程序

  1. 在新浏览器窗口中,登录 Azure 门户
  2. 选择创建资源 > 数据库 > Azure Cosmos DB

  3. 创建 Azure Cosmos DB 帐户页面上,输入新的 Azure Cosmos DB 帐户的基本设置。

    设置 描述
    订阅 您的订阅 选择要用于此 Azure Cosmos DB 帐户的 Azure 订阅。
    资源组 新建

    然后输入与 ID 中提供的相同的唯一名称
    选择新建。然后为您的帐户输入新的资源组名称。为简单起见,请使用与您的 ID 相同的名称。
    科目名称 输入唯一名称 输入一个唯一名称来标识您的 Azure Cosmos DB 帐户。由于 documents.azure.com 会附加到您提供的 ID 以创建 URI,因此请使用唯一 ID。

    ID 只能包含小写字母、数字和连字符 (-) 字符。其长度必须在 3 到 31 个字符之间。
    API Core(SQL) API 决定要创建的帐户类型。Azure Cosmos DB 提供五种 API:用于文档数据库的 Core(SQL)、用于图形数据库的 Gremlin、用于文档数据库的 MongoDB、Azure Table 和 Cassandra。目前,您必须为每个 API 创建一个单独的帐户。

    选择Core(SQL),因为在本文中您将创建一个文档数据库并使用 SQL 语法进行查询。

    详细了解 SQL API.
    Location 选择离您的用户最近的区域 选择一个托管您的 Azure Cosmos DB 帐户的地理位置。使用离您的用户最近的位置,以便他们能最快地访问数据。

    选择审查+创建。您可以跳过网络标记部分。

  4. 帐户创建需要几分钟时间。等待门户显示恭喜!您的 Azure Cosmos DB 帐户已创建页面。

设置您的 Node.js 应用程序

在开始编写代码来构建应用程序之前,您可以构建应用程序的框架。运行以下步骤来设置您的 Node.js 应用程序,该应用程序具有框架代码:

  1. 打开您喜欢的终端。
  2. 找到您希望保存 Node.js 应用程序的文件夹或目录。
  3. 使用以下命令创建两个空的 JavaScript 文件:

    • Windows

      • fsutil file createnew app.js 0
      • fsutil file createnew config.js 0
    • Linux/OS X

      • touch app.js
      • touch config.js
  4. 通过 npm 安装 @azure/cosmos 模块。使用以下命令:

    • npm install @azure/cosmos --save

设置您的应用程序配置

现在您的应用程序已经存在,您需要确保它可以与 Azure Cosmos DB 通信。通过更新一些配置设置,如以下步骤所示,您可以将应用程序设置为与 Azure Cosmos DB 通信:

  1. 在您喜欢的文本编辑器中打开 config.js

  2. 复制并粘贴下面的代码片段,并将属性 config.endpointconfig.primaryKey 设置为您的 Azure Cosmos DB 终结点 URI 和主密钥。这两个配置都可以在Azure 门户中找到。

    // ADD THIS PART TO YOUR CODE
    var config = {}
    
    config.endpoint = "~your Azure Cosmos DB endpoint uri here~";
    config.primaryKey = "~your primary key here~";
    
  3. 复制并粘贴 databasecontaineritems 数据到您设置 config.endpointconfig.primaryKey 属性的 config 对象下方。如果您已经有希望存储在数据库中的数据,您可以使用 Azure Cosmos DB 中的数据迁移工具,而不是在此处定义数据。

    var config = {}
    
    config.endpoint = "~your Azure Cosmos DB account endpoint uri here~";
    config.primaryKey = "~your primary key here~";
    
    config.database = {
       "id": "FamilyDatabase"
    };
    
    config.container = {
      "id": "FamilyContainer"
    };
    
    config.items = {
       "Andersen": {
           "id": "Anderson.1",
           "lastName": "Andersen",
           "parents": [{
             "firstName": "Thomas"
         }, {
                 "firstName": "Mary Kay"
             }],
         "children": [{
             "firstName": "Henriette Thaulow",
             "gender": "female",
             "grade": 5,
             "pets": [{
                 "givenName": "Fluffy"
             }]
         }],
         "address": {
             "state": "WA",
             "county": "King",
             "city": "Seattle"
         }
     },
     "Wakefield": {
         "id": "Wakefield.7",
         "parents": [{
             "familyName": "Wakefield",
             "firstName": "Robin"
         }, {
                 "familyName": "Miller",
                 "firstName": "Ben"
             }],
         "children": [{
             "familyName": "Merriam",
             "firstName": "Jesse",
             "gender": "female",
             "grade": 8,
             "pets": [{
                 "givenName": "Goofy"
             }, {
                     "givenName": "Shadow"
                 }]
         }, {
                 "familyName": "Miller",
                 "firstName": "Lisa",
                 "gender": "female",
                 "grade": 1
             }],
         "address": {
             "state": "NY",
             "county": "Manhattan",
             "city": "NY"
         },
         "isRegistered": false
       }
    };
    

    JavaScript SDK 使用通用术语 containeritem。容器可以是集合、图形或表。项目可以是文档、边缘/顶点或行,并且是容器内部的内容。

  4. 最后,导出您的 config 对象,以便您可以在 app.js 文件中引用它。

         },
         "isRegistered": false
        }
    };
    
    // ADD THIS PART TO YOUR CODE
    module.exports = config;
    

连接到 Azure Cosmos DB 帐户

  1. 在文本编辑器中打开空的 app.js 文件。复制并粘贴下面的代码以导入 @azure/cosmos 模块和您新创建的 config 模块。

    // ADD THIS PART TO YOUR CODE
    const CosmosClient = require('@azure/cosmos').CosmosClient;
    
    const config = require('./config');
    const url = require('url');
    
  2. 复制并粘贴代码以使用之前保存的 config.endpointconfig.primaryKey 创建一个新的 CosmosClient

    const url = require('url');
    
    // ADD THIS PART TO YOUR CODE
    const endpoint = config.endpoint;
    const masterKey = config.primaryKey;
    
    const client = new CosmosClient({ endpoint: endpoint, auth: { masterKey: masterKey } });
    

现在您已经有了初始化 Azure Cosmos DB 客户端的代码,让我们看看如何使用 Azure Cosmos DB 资源。

创建数据库

  1. 复制并粘贴下面的代码来设置数据库 ID 和容器 ID。这些 ID 是 Azure Cosmos DB 客户端查找正确的数据库和容器的方式。

    const client = new CosmosClient({ endpoint: endpoint, auth: { masterKey: masterKey } });
    
    // ADD THIS PART TO YOUR CODE
    const HttpStatusCodes = { NOTFOUND: 404 };
    
    const databaseId = config.database.id;
    const containerId = config.container.id;
    

    数据库可以使用 Databases 类的 createIfNotExists 或 create 函数创建。数据库是跨容器分区的数据项的逻辑容器。

  2. createDatabasereadDatabase 方法复制并粘贴到 app.js 文件中 databaseIdcontainerId 定义下方。如果数据库不存在,createDatabase 函数将使用 config 对象中指定的 ID FamilyDatabase 创建一个新数据库。readDatabase 函数将读取数据库的定义以确保数据库存在。

    /**
     * Create the database if it does not exist
     */
    async function createDatabase() {
        const { database } = await client.databases.createIfNotExists({ id: databaseId });
        console.log(`Created database:\n${database.id}\n`);
    }
    
    /**
    * Read the database definition
    */
    async function readDatabase() {
       const { body: databaseDefinition } = await client.database(databaseId).read();
       console.log(`Reading database:\n${databaseDefinition.id}\n`);
    }
    
  3. 复制并粘贴 createDatabasereadDatabase 函数下方的代码,以添加将打印退出消息的辅助函数 exit

    // ADD THIS PART TO YOUR CODE
    function exit(message) {
       console.log(message);
       console.log('Press any key to exit');
       process.stdin.setRawMode(true);
       process.stdin.resume();
       process.stdin.on('data', process.exit.bind(process, 0));
    };
    
  4. 复制并粘贴 exit 函数下方的代码,以调用 createDatabasereadDatabase 函数。

    createDatabase()
      .then(() => readDatabase())
      .then(() => { exit(`Completed successfully`); })
      .catch((error) => { exit(`Completed with error \${JSON.stringify(error)}`) });
    

    此时,您的 app.js 代码应如下所示:

    const CosmosClient = require('@azure/cosmos').CosmosClient;
    
    const config = require('./config');
    const url = require('url');
    
    const endpoint = config.endpoint;
    const masterKey = config.primaryKey;
    
    const client = new CosmosClient({ endpoint: endpoint, auth: { masterKey: masterKey } });
    
    const HttpStatusCodes = { NOTFOUND: 404 };
    
    const databaseId = config.database.id;
    const containerId = config.container.id;
    
     /**
     * Create the database if it does not exist
     */
     async function createDatabase() {
      const { database } = await client.databases.createIfNotExists({ id: databaseId });
      console.log(`Created database:\n${database.id}\n`);
    }
    
    /**
    * Read the database definition
    */
    async function readDatabase() {
      const { body: databaseDefinition } = await client.database(databaseId).read();
     console.log(`Reading database:\n${databaseDefinition.id}\n`);
    }
    
    /**
    * Exit the app with a prompt
    * @param {message} message - The message to display
    */
    function exit(message) {
      console.log(message);
      console.log('Press any key to exit');
      process.stdin.setRawMode(true);
      process.stdin.resume();
      process.stdin.on('data', process.exit.bind(process, 0));
    }
    
    createDatabase()
      .then(() => readDatabase())
      .then(() => { exit(`Completed successfully`); })
      .catch((error) => { exit(`Completed with error ${JSON.stringify(error) }`) });
    
  5. 在您的终端中,找到您的 app.js 文件并运行命令:

    node app.js
    

创建容器

接下来在 Azure Cosmos DB 帐户中创建一个容器,以便您可以存储和查询数据。

警告

创建容器会产生价格影响。访问我们的定价页面,以便您知道会发生什么。

容器可以使用 Containers 类的 createIfNotExists 或 create 函数创建。容器包含项目(在 SQL API 的情况下是 JSON 文档)和相关的 JavaScript 应用程序逻辑。

  1. createContainerreadContainer 函数复制并粘贴到 app.js 文件中 readDatabase 函数下方。如果容器不存在,createContainer 函数将使用 config 对象中指定的 containerId 创建一个新容器。readContainer 函数将读取容器定义以验证容器是否存在。

    /**
    * Create the container if it does not exist
    */
    async function createContainer() {
     const { container } = await client.database(databaseId).containers.createIfNotExists({ id: containerId });
     console.log(`Created container:\n${config.container.id}\n`);
    }
    
    /**
    * Read the container definition
    */
    async function readContainer() {
      const { body: containerDefinition } = await client.database(databaseId).container(containerId).read();
      console.log(`Reading container:\n${containerDefinition.id}\n`);
    }
    
  2. 复制并粘贴 readDatabase 调用下方的代码以执行 createContainerreadContainer 函数。

    createDatabase()
      .then(() => readDatabase())
    
      // ADD THIS PART TO YOUR CODE
      .then(() => createContainer())
      .then(() => readContainer())
      // ENDS HERE
    
      .then(() => { exit(`Completed successfully`); })
      .catch((error) => { exit(`Completed with error ${JSON.stringify(error)}`) });
    

    此时,您的 app.js 代码应如下所示:

    const CosmosClient = require('@azure/cosmos').CosmosClient;
    
    const config = require('./config');
    const url = require('url');
    
    const endpoint = config.endpoint;
    const masterKey = config.primaryKey;
    
    const client = new CosmosClient({ endpoint: endpoint, auth: { masterKey: masterKey } });
    
    const HttpStatusCodes = { NOTFOUND: 404 };
    
    const databaseId = config.database.id;
    const containerId = config.container.id;
    
    /**
    * Create the database if it does not exist
    */
    async function createDatabase() {
      const { database } = await client.databases.createIfNotExists({ id: databaseId });
      console.log(`Created database:\n${database.id}\n`);
    }
    
    /**
    * Read the database definition
    */
    async function readDatabase() {
      const { body: databaseDefinition } = await client.database(databaseId).read();
      console.log(`Reading database:\n${databaseDefinition.id}\n`);
    }
    
    /**
    * Create the container if it does not exist
    */
    async function createContainer() {
      const { container } = await client.database(databaseId).containers.createIfNotExists({ id: containerId });
      console.log(`Created container:\n${config.container.id}\n`);
    }
    
    /**
    * Read the container definition
    */
    async function readContainer() {
      const { body: containerDefinition } = await client.database(databaseId).container(containerId).read();
      console.log(`Reading container:\n${containerDefinition.id}\n`);
    }
    
    /**
    * Exit the app with a prompt
    * @param {message} message - The message to display
    */
    function exit(message) {
      console.log(message);
      console.log('Press any key to exit');
      process.stdin.setRawMode(true);
      process.stdin.resume();
      process.stdin.on('data', process.exit.bind(process, 0));
    }
    
    createDatabase()
      .then(() => readDatabase())
      .then(() => createContainer())
      .then(() => readContainer())
      .then(() => { exit(`Completed successfully`); })
      .catch((error) => { exit(`Completed with error ${JSON.stringify(error)}`) });
    
  3. 在您的终端中,找到您的 app.js 文件并运行命令:

    node app.js
    

创建项目

项目可以使用 Items 类的 create 函数创建。当您使用 SQL API 时,项目以文档形式呈现,这些文档是用户定义的(任意)JSON 内容。您现在可以将项目插入到 Azure Cosmos DB 中。

  1. createFamilyItem 函数复制并粘贴到 readContainer 函数下方。createFamilyItem 函数创建包含保存在 config 对象中的 JSON 数据的项目。我们将在创建项目之前检查以确保具有相同 ID 的项目尚不存在。

    /**
    * Create family item if it does not exist
    */
    async function createFamilyItem(itemBody) {
      try {
          // read the item to see if it exists
          const { item } = await client.database(databaseId).container(containerId).item(itemBody.id).read();
          console.log(`Item with family id ${itemBody.id} already exists\n`);
      }
      catch (error) {
         // create the family item if it does not exist
         if (error.code === HttpStatusCodes.NOTFOUND) {
             const { item } = await client.database(databaseId).container(containerId).items.create(itemBody);
             console.log(`Created family item with id:\n${itemBody.id}\n`);
         } else {
             throw error;
         }
      }
    };
    
  2. 复制并粘贴 readContainer 调用下方的代码以执行 createFamilyItem 函数。

    createDatabase()
      .then(() => readDatabase())
      .then(() => createContainer())
      .then(() => readContainer())
    
      // ADD THIS PART TO YOUR CODE
      .then(() => createFamilyItem(config.items.Andersen))
      .then(() => createFamilyItem(config.items.Wakefield))
      // ENDS HERE
    
      .then(() => { exit(`Completed successfully`); })
      .catch((error) => { exit(`Completed with error ${JSON.stringify(error)}`) });
    
  3. 在您的终端中,找到您的 app.js 文件并运行命令:

    node app.js
    

查询 Azure Cosmos DB 资源

Azure Cosmos DB 支持对每个容器中存储的 JSON 文档进行丰富的查询。以下示例代码显示了您可以针对容器中的文档运行的查询。

  1. queryContainer 函数复制并粘贴到 app.js 文件中 createFamilyItem 函数下方。Azure Cosmos DB 支持类似 SQL 的查询,如下所示。

    /**
    * Query the container using SQL
     */
    async function queryContainer() {
      console.log(`Querying container:\n${config.container.id}`);
    
      // query to return all children in a family
      const querySpec = {
         query: "SELECT VALUE r.children FROM root r WHERE r.lastName = @lastName",
         parameters: [
             {
                 name: "@lastName",
                 value: "Andersen"
             }
         ]
     };
    
     const { result: results } = await client.database(databaseId).container(containerId).items.query(querySpec).toArray();
     for (var queryResult of results) {
         let resultString = JSON.stringify(queryResult);
         console.log(`\tQuery returned ${resultString}\n`);
     }
    };
    
  2. 复制并粘贴 createFamilyItem 调用下方的代码以执行 queryContainer 函数。

    createDatabase()
      .then(() => readDatabase())
      .then(() => createContainer())
      .then(() => readContainer())
      .then(() => createFamilyItem(config.items.Andersen))
      .then(() => createFamilyItem(config.items.Wakefield))
    
      // ADD THIS PART TO YOUR CODE
      .then(() => queryContainer())
      // ENDS HERE
    
      .then(() => { exit(`Completed successfully`); })
      .catch((error) => { exit(`Completed with error ${JSON.stringify(error)}`) });
    
  3. 在您的终端中,找到您的 app.js 文件并运行命令:

    node app.js
    

替换项目

Azure Cosmos DB 支持替换项目的内容。

  1. replaceFamilyItem 函数复制并粘贴到 app.js 文件中 queryContainer 函数下方。请注意,我们已将子项的“grade”属性从之前的值 5 更改为 6。

    // ADD THIS PART TO YOUR CODE
    /**
    * Replace the item by ID.
    */
    async function replaceFamilyItem(itemBody) {
       console.log(`Replacing item:\n${itemBody.id}\n`);
       // Change property 'grade'
       itemBody.children[0].grade = 6;
       const { item } = await client.database(databaseId).container(containerId).item(itemBody.id).replace(itemBody);
    };
    
  2. 复制并粘贴 queryContainer 调用下方的代码以执行 replaceFamilyItem 函数。此外,添加代码再次调用 queryContainer 以验证项目已成功更改。

    createDatabase()
      .then(() => readDatabase())
      .then(() => createContainer())
      .then(() => readContainer())
      .then(() => createFamilyItem(config.items.Andersen))
      .then(() => createFamilyItem(config.items.Wakefield))
      .then(() => queryContainer())
    
      // ADD THIS PART TO YOUR CODE
      .then(() => replaceFamilyItem(config.items.Andersen))
      .then(() => queryContainer())
      // ENDS HERE
    
      .then(() => { exit(`Completed successfully`); })
      .catch((error) => { exit(`Completed with error ${JSON.stringify(error)}`) });
    
  3. 在您的终端中,找到您的 app.js 文件并运行命令:

    node app.js
    

删除项目

Azure Cosmos DB 支持删除 JSON 项目。

  1. deleteFamilyItem 函数复制并粘贴到 replaceFamilyItem 函数下方。

    /**
    * Delete the item by ID.
    */
    async function deleteFamilyItem(itemBody) {
       await client.database(databaseId).container(containerId).item(itemBody.id).delete(itemBody);
       console.log(`Deleted item:\n${itemBody.id}\n`);
    };
    
  2. 复制并粘贴第二个 queryContainer 调用下方的代码以执行 deleteFamilyItem 函数。

    createDatabase()
       .then(() => readDatabase())
       .then(() => createContainer())
       .then(() => readContainer())
       .then(() => createFamilyItem(config.items.Andersen))
       .then(() => createFamilyItem(config.items.Wakefield))
       .then(() => queryContainer
       ())
       .then(() => replaceFamilyItem(config.items.Andersen))
       .then(() => queryContainer())
    
     // ADD THIS PART TO YOUR CODE
       .then(() => deleteFamilyItem(config.items.Andersen))
     // ENDS HERE
    
     .then(() => { exit(`Completed successfully`); })
     .catch((error) => { exit(`Completed with error ${JSON.stringify(error)}`) });
    
  3. 在您的终端中,找到您的 app.js 文件并运行命令:

    node app.js
    

删除数据库

删除创建的数据库将删除数据库及其所有子资源(容器、项目等)。

  1. cleanup 函数复制并粘贴到 deleteFamilyItem 函数下方,以删除数据库及其所有子资源。

    /**
    * Cleanup the database and container on completion
    */
    async function cleanup() {
      await client.database(databaseId).delete();
    }
    
  2. 复制并粘贴 deleteFamilyItem 调用下方的代码以执行 cleanup 函数。

    createDatabase()
       .then(() => readDatabase())
       .then(() => createContainer())
       .then(() => readContainer())
       .then(() => createFamilyItem(config.items.Andersen))
       .then(() => createFamilyItem(config.items.Wakefield))
       .then(() => queryContainer())
       .then(() => replaceFamilyItem(config.items.Andersen))
       .then(() => queryContainer())
       .then(() => deleteFamilyItem(config.items.Andersen))
    
       // ADD THIS PART TO YOUR CODE
       .then(() => cleanup())
       // ENDS HERE
    
       .then(() => { exit(`Completed successfully`); })
       .catch((error) => { exit(`Completed with error ${JSON.stringify(error)}`) });
    

运行您的 Node.js 应用程序

总而言之,您的代码应如下所示:

const CosmosClient = require('@azure/cosmos').CosmosClient;

const config = require('./config');
const url = require('url');

const endpoint = config.endpoint;
const masterKey = config.primaryKey;

const HttpStatusCodes = { NOTFOUND: 404 };

const databaseId = config.database.id;
const containerId = config.container.id;

const client = new CosmosClient({ endpoint: endpoint, auth: { masterKey: masterKey } });

/**
 * Create the database if it does not exist
 */
async function createDatabase() {
    const { database } = await client.databases.createIfNotExists({ id: databaseId });
    console.log(`Created database:\n${database.id}\n`);
}

/**
 * Read the database definition
 */
async function readDatabase() {
    const { body: databaseDefinition } = await client.database(databaseId).read();
    console.log(`Reading database:\n${databaseDefinition.id}\n`);
}

/**
 * Create the container if it does not exist
 */
async function createContainer() {
    const { container } = await client.database(databaseId).containers.createIfNotExists({ id: containerId });
    console.log(`Created container:\n${config.container.id}\n`);
}

/**
 * Read the container definition
 */
async function readContainer() {
    const { body: containerDefinition } = await client.database(databaseId).container(containerId).read();
    console.log(`Reading container:\n${containerDefinition.id}\n`);
}

/**
 * Create family item if it does not exist
 */
async function createFamilyItem(itemBody) {
    try {
        // read the item to see if it exists
        const { item } = await client.database(databaseId).container(containerId).item(itemBody.id).read();
        console.log(`Item with family id ${itemBody.id} already exists\n`);
    }
    catch (error) {
        // create the family item if it does not exist
        if (error.code === HttpStatusCodes.NOTFOUND) {
            const { item } = await client.database(databaseId).container(containerId).items.create(itemBody);
            console.log(`Created family item with id:\n${itemBody.id}\n`);
        } else {
            throw error;
        }
    }
};

/**
 * Query the container using SQL
 */
async function queryContainer() {
    console.log(`Querying container:\n${config.container.id}`);

    // query to return all children in a family
    const querySpec = {
        query: "SELECT VALUE r.children FROM root r WHERE r.lastName = @lastName",
        parameters: [
            {
                name: "@lastName",
                value: "Andersen"
            }
        ]
    };

    const { result: results } = await client.database(databaseId).container(containerId).items.query(querySpec).toArray();
    for (var queryResult of results) {
        let resultString = JSON.stringify(queryResult);
        console.log(`\tQuery returned ${resultString}\n`);
    }
};

/**
 * Replace the item by ID.
 */
async function replaceFamilyItem(itemBody) {
    console.log(`Replacing item:\n${itemBody.id}\n`);
    // Change property 'grade'
    itemBody.children[0].grade = 6;
    const { item } = await client.database(databaseId).container(containerId).item(itemBody.id).replace(itemBody);
};

/**
 * Delete the item by ID.
 */
async function deleteFamilyItem(itemBody) {
    await client.database(databaseId).container(containerId).item(itemBody.id).delete(itemBody);
    console.log(`Deleted item:\n${itemBody.id}\n`);
};

/**
 * Cleanup the database and container on completion
 */
async function cleanup() {
    await client.database(databaseId).delete();
}

/**
 * Exit the app with a prompt
 * @param {message} message - The message to display
 */
function exit(message) {
    console.log(message);
    console.log('Press any key to exit');
    process.stdin.setRawMode(true);
    process.stdin.resume();
    process.stdin.on('data', process.exit.bind(process, 0));
}

createDatabase()
    .then(() => readDatabase())
    .then(() => createContainer())
    .then(() => readContainer())
    .then(() => createFamilyItem(config.items.Andersen))
    .then(() => createFamilyItem(config.items.Wakefield))
    .then(() => queryContainer())
    .then(() => replaceFamilyItem(config.items.Andersen))
    .then(() => queryContainer())
    .then(() => deleteFamilyItem(config.items.Andersen))
    .then(() => cleanup())
    .then(() => { exit(`Completed successfully`); })
    .catch((error) => { exit(`Completed with error ${JSON.stringify(error)}`) });

在您的终端中,找到您的 app.js 文件并运行命令:

node app.js

您应该看到您的入门应用程序的输出。输出应与下面的示例文本匹配。

 Created database:
 FamilyDatabase

 Reading database:
 FamilyDatabase

 Created container:
 FamilyContainer

 Reading container:
 FamilyContainer

 Created family item with id:
 Anderson.1

 Created family item with id:
 Wakefield.7

 Querying container:
 FamilyContainer
         Query returned [{"firstName":"Henriette Thaulow","gender":"female","grade":5,"pets":[{"givenName":"Fluffy"}]}]

 Replacing item:
 Anderson.1

 Querying container:
 FamilyContainer
         Query returned [{"firstName":"Henriette Thaulow","gender":"female","grade":6,"pets":[{"givenName":"Fluffy"}]}]

 Deleted item:
 Anderson.1

 Completed successfully
 Press any key to exit

获取完整的 Node.js 教程解决方案

如果您没有时间完成本教程中的步骤,或者只想下载代码,可以从GitHub获取。

要运行包含本文所有代码的入门解决方案,您需要:

通过 npm 安装 @azure/cosmos 模块。使用以下命令:

  • npm install @azure/cosmos --save

接下来,在 config.js 文件中,按照步骤 3:设置您的应用程序配置中所述更新 config.endpoint 和 config.primaryKey 值。

然后在您的终端中,找到您的 app.js 文件并运行命令:

node app.js 

清理资源

当不再需要这些资源时,您可以删除资源组、Azure Cosmos DB 帐户和所有相关资源。为此,请选择用于 Azure Cosmos DB 帐户的资源组,选择删除,然后确认要删除的资源组的名称。

© . All rights reserved.