Skip to content

Commit 88b777f

Browse files
committed
Fixing Node.js tutorial
1 parent 3feec5b commit 88b777f

File tree

2 files changed

+31
-160
lines changed

2 files changed

+31
-160
lines changed

articles/cosmos-db/TOC.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
href: sql-api-java-get-started.md
4040
- name: Async Java
4141
href: sql-api-async-java-get-started.md
42-
- name: Async Java end-to-end sample app
42+
- name: Async Java sample with change feed
4343
href: create-sql-api-java-changefeed.md
4444
- name: Node.js
4545
href: sql-api-nodejs-get-started.md

articles/cosmos-db/sql-api-nodejs-get-started.md

Lines changed: 30 additions & 159 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ ms.service: cosmos-db
66
ms.subservice: cosmosdb-sql
77
ms.devlang: nodejs
88
ms.topic: tutorial
9-
ms.date: 08/06/2019
9+
ms.date: 04/20/2020
1010
ms.author: dech
1111
Customer intent: As a developer, I want to build a Node.js console application to access and manage SQL API account resources in Azure Cosmos DB, so that customers can better use the service.
1212

@@ -54,15 +54,19 @@ Before you start writing code to build the application, you can build the framew
5454

5555
1. Open your favorite terminal.
5656
2. Locate the folder or directory where you'd like to save your Node.js application.
57-
3. Create two empty JavaScript files with the following commands:
57+
3. Create empty JavaScript files with the following commands:
5858

5959
* Windows:
60-
* ```fsutil file createnew app.js 0```
61-
* ```fsutil file createnew config.js 0```
60+
* `fsutil file createnew app.js 0`
61+
* `fsutil file createnew config.js 0`
62+
* `md data`
63+
* `fsutil file createnew data\databaseContext.js 0`
6264

6365
* Linux/OS X:
64-
* ```touch app.js```
65-
* ```touch config.js```
66+
* `touch app.js`
67+
* `touch config.js`
68+
* `mkdir data`
69+
* `touch data/databaseContext.js`
6670

6771
4. Create and initialize a `package.json` file. Use the following command:
6872
* ```npm init -y```
@@ -74,31 +78,21 @@ Before you start writing code to build the application, you can build the framew
7478

7579
Now that your app exists, you need to make sure it can talk to 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:
7680

77-
1. Open ```config.js``` in your favorite text editor.
81+
1. Open the *config.js* file in your favorite text editor.
7882

79-
1. Copy and paste the code snippet below and set properties ```config.endpoint``` and ```config.key``` to your Azure Cosmos DB endpoint URI and primary key. Both these configurations can be found in the [Azure portal](https://portal.azure.com).
83+
1. 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. The database, container names are set to **Tasks** and **Items**. The partition key you will use for this application is **/category**.
8084

81-
![Get keys from Azure portal screenshot][keys]
82-
83-
```javascript
84-
// ADD THIS PART TO YOUR CODE
85-
var config = {}
86-
87-
config.endpoint = "~your Azure Cosmos DB endpoint uri here~";
88-
config.key = "~your primary key here~";
89-
```
85+
:::code language="javascript" source="~/cosmosdb-nodejs-get-started/config.js":::
9086

91-
1. Copy and paste the ```database```, ```container```, and ```items``` data to your ```config``` object below where you set your ```config.endpoint``` and ```config.key``` properties. If you already have data you'd like to store in your database, you can use the Data Migration tool in Azure Cosmos DB rather than defining the data here. You config.js file should have the following code:
87+
You can find the endpoint and key details in the **Keys** pane of the [Azure portal](https://portal.azure.com).
9288

93-
:::code language="javascript" source="~/cosmosdb-nodejs-get-started/config.js":::
89+
![Get keys from Azure portal screenshot][keys]
9490

95-
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.
96-
97-
`module.exports = config;` code is used to export your ```config``` object, so that you can reference it within the ```app.js``` file.
91+
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. 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.
9892

9993
## <a id="Connect"></a>Connect to an Azure Cosmos DB account
10094

101-
1. Open your empty ```app.js``` file in the text editor. Copy and paste the code below to import the ```@azure/cosmos``` module and your newly created ```config``` module.
95+
1. Open the *app.js* file in a text editor. Copy and paste the code below to import the ```@azure/cosmos``` module and your newly created ```config``` module.
10296

10397
```javascript
10498
// ADD THIS PART TO YOUR CODE
@@ -120,30 +114,31 @@ Now that your app exists, you need to make sure it can talk to Azure Cosmos DB.
120114
```
121115

122116
> [!Note]
123-
> If connecting to the **Cosmos DB Emulator**, disable TLS verification for your node process:
117+
> If you are connecting to the **Cosmos DB Emulator** instead of the Azure Cosmos account in Azure portal, make sure to disable the TLS verification. You can disable the TLS verification for your node process with the following code:
124118
> ```
125119
> process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
126120
> const client = new CosmosClient({ endpoint, key });
127121
> ```
128122
129123
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.
130124
131-
## Create a database
125+
## Create a database and a container
126+
127+
1. Open the *databaseContext.js* file in your favorite text editor.
128+
129+
1. Copy and paste the following code to the *databaseContext.js* file. 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:
130+
131+
:::code language="javascript" source="~/cosmosdb-nodejs-get-started/data/databaseContext.js" id="createDatabaseAndContainer":::
132+
133+
A database is the logical container of items partitioned across containers. You create a database by using either the `createIfNotExists` or create function of the **Databases** class. A container consists of items which in the case of the SQL API is JSON documents. 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.
134+
135+
> [!WARNING]
136+
> Creating a container has pricing implications. Visit our [pricing page](https://azure.microsoft.com/pricing/details/cosmos-db/) so you know what to expect.
132137
133-
1. Copy and paste the code below to set the database ID, and the container ID. These IDs are how the Azure Cosmos DB client will find the right database and container.
134138
135-
```javascript
136-
const client = new CosmosClient({ endpoint, key });
137139
138-
// ADD THIS PART TO YOUR CODE
139-
const HttpStatusCodes = { NOTFOUND: 404 };
140140
141-
const databaseId = config.database.id;
142-
const containerId = config.container.id;
143-
const partitionKey = { kind: "Hash", paths: ["/Country"] };
144-
```
145141
146-
A database can be created by using either the `createIfNotExists` or create function of the **Databases** class. A database is the logical container of items partitioned across containers.
147142
148143
2. Copy and paste the **createDatabase** and **readDatabase** methods into the app.js file under the ```databaseId``` and ```containerId``` definition. The **createDatabase** function will create a new database with ID ```FamilyDatabase```, specified from the ```config``` object if it does not already exist. The **readDatabase** function will read the database's definition to ensure that the database exists.
149144
@@ -187,58 +182,6 @@ Now that you have the code to initialize the Azure Cosmos DB client, let's take
187182
.catch((error) => { exit(`Completed with error \${JSON.stringify(error)}`) });
188183
```
189184

190-
At this point, your code in ```app.js``` should now look as following code:
191-
192-
```javascript
193-
const CosmosClient = require('@azure/cosmos').CosmosClient;
194-
195-
const config = require('./config');
196-
197-
const endpoint = config.endpoint;
198-
const key = config.key;
199-
200-
const client = new CosmosClient({ endpoint, key });
201-
202-
const HttpStatusCodes = { NOTFOUND: 404 };
203-
204-
const databaseId = config.database.id;
205-
const containerId = config.container.id;
206-
const partitionKey = { kind: "Hash", paths: ["/Country"] };
207-
208-
/**
209-
* Create the database if it does not exist
210-
*/
211-
async function createDatabase() {
212-
const { database } = await client.databases.createIfNotExists({ id: databaseId });
213-
console.log(`Created database:\n${database.id}\n`);
214-
}
215-
216-
/**
217-
* Read the database definition
218-
*/
219-
async function readDatabase() {
220-
const { resource: databaseDefinition } = await client.database(databaseId).read();
221-
console.log(`Reading database:\n${databaseDefinition.id}\n`);
222-
}
223-
224-
/**
225-
* Exit the app with a prompt
226-
* @param {message} message - The message to display
227-
*/
228-
function exit(message) {
229-
console.log(message);
230-
console.log('Press any key to exit');
231-
process.stdin.setRawMode(true);
232-
process.stdin.resume();
233-
process.stdin.on('data', process.exit.bind(process, 0));
234-
}
235-
236-
createDatabase()
237-
.then(() => readDatabase())
238-
.then(() => { exit(`Completed successfully`); })
239-
.catch((error) => { exit(`Completed with error ${JSON.stringify(error) }`) });
240-
```
241-
242185
5. In your terminal, locate your ```app.js``` file and run the command:
243186

244187
```bash
@@ -291,78 +234,6 @@ A container can be created by using either the `createIfNotExists` or create fun
291234
.catch((error) => { exit(`Completed with error ${JSON.stringify(error)}`) });
292235
```
293236

294-
At this point, your code in ```app.js``` should now look like this:
295-
296-
```javascript
297-
const CosmosClient = require('@azure/cosmos').CosmosClient;
298-
299-
const config = require('./config');
300-
301-
const endpoint = config.endpoint;
302-
const key = config.key;
303-
304-
const client = new CosmosClient({ endpoint, key });
305-
306-
const HttpStatusCodes = { NOTFOUND: 404 };
307-
308-
const databaseId = config.database.id;
309-
const containerId = config.container.id;
310-
const partitionKey = { kind: "Hash", paths: ["/Country"] };
311-
312-
/**
313-
* Create the database if it does not exist
314-
*/
315-
async function createDatabase() {
316-
const { database } = await client.databases.createIfNotExists({ id: databaseId });
317-
console.log(`Created database:\n${database.id}\n`);
318-
}
319-
320-
/**
321-
* Read the database definition
322-
*/
323-
async function readDatabase() {
324-
const { body: databaseDefinition } = await client.database(databaseId).read();
325-
console.log(`Reading database:\n${databaseDefinition.id}\n`);
326-
}
327-
328-
/**
329-
* Create the container if it does not exist
330-
*/
331-
332-
async function createContainer() {
333-
334-
const { container } = await client.database(databaseId).containers.createIfNotExists({ id: containerId, partitionKey }, { offerThroughput: 400 });
335-
console.log(`Created container:\n${config.container.id}\n`);
336-
}
337-
338-
/**
339-
* Read the container definition
340-
*/
341-
async function readContainer() {
342-
const { resource: containerDefinition } = await client.database(databaseId).container(containerId).read();
343-
console.log(`Reading container:\n${containerDefinition.id}\n`);
344-
}
345-
346-
/**
347-
* Exit the app with a prompt
348-
* @param {message} message - The message to display
349-
*/
350-
function exit(message) {
351-
console.log(message);
352-
console.log('Press any key to exit');
353-
process.stdin.setRawMode(true);
354-
process.stdin.resume();
355-
process.stdin.on('data', process.exit.bind(process, 0));
356-
}
357-
358-
createDatabase()
359-
.then(() => readDatabase())
360-
.then(() => createContainer())
361-
.then(() => readContainer())
362-
.then(() => { exit(`Completed successfully`); })
363-
.catch((error) => { exit(`Completed with error ${JSON.stringify(error)}`) });
364-
```
365-
366237
1. In your terminal, locate your ```app.js``` file and run the command:
367238

368239
```bash

0 commit comments

Comments
 (0)