Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit editor mode

Tutorial: Connect a Node.js web app with Azure DocumentDB

Feedback

In this article

In this tutorial, you build a Node.js web application that connects to Azure DocumentDB. The MongoDB, Express, React.js, Node.js (MERN) stack is a popular collection of technologies used to build many modern web applications. With Azure DocumentDB, you can build a new web application or migrate an existing application using MongoDB drivers that you're already familiar with. In this tutorial, you:

  • Set up your environment
  • Test the MERN application with a local MongoDB container
  • Test the MERN application with a cluster
  • Deploy the MERN application to Azure App Service

Prerequisites

To complete this tutorial, you need the following resources:

  • An Azure subscription

    • If you don't have an Azure subscription, create afree account
  • An existing Azure DocumentDB cluster

  • A GitHub account with GitHub Codespaces entitlement

Configure development environment

A development container environment is available with all dependencies required to complete every exercise in this project. You can run the development container in GitHub Codespaces or locally using Visual Studio Code.

GitHub Codespaces runs a development container managed by GitHub with Visual Studio Code for the Web as the user interface. For the most straightforward development environment, use GitHub Codespaces so that you have the correct developer tools and dependencies preinstalled to complete this training module.

Important

All GitHub accounts can use Codespaces for up to 60 hours free each month with two core instances.

  1. Start the process to create a new GitHub Codespace on themain branch of theazure-samples/msdocs-azure-cosmos-db-mongodb-mern-web-app GitHub repository.

    Open in GitHub Codespaces

  2. On theCreate codespace page, review the codespace configuration settings, and then selectCreate new codespace

    Screenshot of the confirmation screen before creating a new codespace.

  3. Wait for the codespace to start. This startup process can take a few minutes.

  4. Open a new terminal in the codespace.

    Tip

    You can use the main menu to navigate to theTerminal menu option and then select theNew Terminal option.

    Screenshot of the devcontainer menu option to open a new terminal.

  5. Check the versions of the tools you use in this tutorial.

    docker --versionnode --versionnpm --versionaz --version

    Note

    This tutorial requires the following versions of each tool, which are preinstalled in your environment:

    ToolVersion
    Docker≥ 20.10.0
    Node.js≥ 18.0150
    npm≥ 9.5.0
    Azure CLI≥ 2.46.0
  6. Close the terminal.

  7. The remaining steps in this tutorial take place in the context of this development container.

Test the MERN application's API with the MongoDB container

Start by running the sample application's API with the local MongoDB container to validate that the application works.

  1. Run a MongoDB container using Docker and publish the typical MongoDB port (27017).

    docker pull mongo:6.0docker run --detach --publish 27017:27017 mongo:6.0
  2. In the side bar, select the MongoDB extension.

    Screenshot of the MongoDB extension in the side bar.

  3. Add a new connection to the MongoDB extension using the connection stringmongodb://localhost.

    Screenshot of the added connection button in the MongoDB extension.

  4. Once the connection is successful, open thedata/products.mongodb playground file.

  5. Select theRun all icon to execute the script.

    Screenshot of the run all button in a playground for the MongoDB extension.

  6. The playground run should result in a list of documents in the local MongoDB collection. Here's a truncated example of the output.

    [  {    "_id": { "$oid": "640a146e89286b79b6628eef" },    "name": "Confira Watch",    "category": "watches",    "price": 105  },  {    "_id": { "$oid": "640a146e89286b79b6628ef0" },    "name": "Diannis Watch",    "category": "watches",    "price": 98,    "sale": true  },  ...]

    Note

    The object identifiers (_id) are randomly generated and differ from this truncated example output.

  7. In theserver/ directory, create a new.env file.

  8. In theserver/.env file, add an environment variable for this value:

    Environment VariableValue
    CONNECTION_STRINGThe connection string to the Azure DocumentDB cluster. For now, usemongodb://localhost:27017?directConnection=true.
    CONNECTION_STRING=mongodb://localhost:27017?directConnection=true
  9. Change the context of the terminal to theserver/ folder.

    cd server
  10. Install the dependencies from Node Package Manager (npm).

    npm install
  11. Start the Node.js & Express application.

    npm start
  12. The API automatically opens a browser window to verify that it returns an array of product documents.

  13. Close the extra browser tab/window.

  14. Close the terminal.

Test the MERN application with the Azure DocumentDB cluster

Now, let's validate that the application works seamlessly with Azure DocumentDB. For this task, populate the preexisting cluster with seed data using the MongoDB shell and then update the API's connection string.

  1. Sign in to the Azure portal (https://portal.azure.com).

  2. Navigate to the existing Azure DocumentDB cluster page.

  3. From the Azure DocumentDB cluster page, select theConnection strings navigation menu option.

    Screenshot of the connection strings option on the page for a cluster.

  4. Record the value from theConnection string field.

    Screenshot of the connection string credential for a cluster.

    Important

    The connection string in the portal doesn't include the username and password values. You must replace the<user> and<password> placeholders with the credentials you used when you originally created the cluster.

  5. Open a new terminal within your integrated development environment (IDE).

  6. Start the MongoDB Shell using themongosh command and the connection string you recorded earlier. Make sure you replace the<user> and<password> placeholders with the credentials you used when you originally created the cluster.

    mongosh "<mongodb-cluster-connection-string>"

    Note

    You could need to encode specific values for the connection string. In this example, the name of the cluster ismsdocs-azure-documentdb-tutorial, the username isclusteradmin, and the password isP@ssw.rd. In the password, the@ character needs to be encoded using%40. An example connection string is provided here with the correct encoding of the password.

    CONNECTION_STRING=mongodb+srv://clusteradmin:P%40ssw.rd@msdocs-azure-documentdb-tutorial.mongocluster.cosmos.azure.com/?tls=true&authMechanism=SCRAM-SHA-256&retrywrites=false&maxIdleTimeMS=120000
  7. Within the shell, run the following commands to create your database, create your collection, and seed with starter data.

    use('cosmicworks');db.products.drop();db.products.insertMany([  { name: "Confira Watch", category: "watches", price: 105.00 },  { name: "Diannis Watch", category: "watches", price: 98.00, sale: true },  { name: "Sterse Gloves", category: "gloves", price: 42.00 },  { name: "Peache Sunglasses", category: "eyewear", price: 32.00, sale: false, sizes: [ "S", "M", "L" ] },  { name: "Icento Pack", category: "bags", price: 58.00 },  { name: "Iroowl Bracelet", category: "watches", price: 66.00 },  { name: "Glaark Bag", category: "bags", price: 56.00, sale: true },  { name: "Windry Mittens", category: "gloves", price: 35.00 },  { name: "Tuvila Hat", category: "hats", price: 120.00 },  { name: "Klinto Hat", category: "hats", subcategory: "hats-beanies", price: 65.00 }]);db.products.find({});
  8. The commands should result in a list of documents in the local MongoDB collection. Here's a truncated example of the output.

    [  {    "_id": { "$oid": "640a146e89286b79b6628eef" },    "name": "Confira Watch",    "category": "watches",    "price": 105  },  {    "_id": { "$oid": "640a146e89286b79b6628ef0" },    "name": "Diannis Watch",    "category": "watches",    "price": 98,    "sale": true  },  ...]

    Note

    The object identifiers (_id) are randomly generated and differ from this truncated example output.

  9. Exit the MongoDB shell.

    exit
  10. In theclient/ directory, create a new.env file.

  11. In theclient/.env file, add an environment variable for this value:

    Environment VariableValue
    CONNECTION_STRINGThe connection string to the Azure DocumentDB cluster. Use the same connection string you used with the mongo shell.
    CONNECTION_STRING=<your-connection-string>
  12. Validate that the application is using the database service by changing the context of the terminal to theserver/ folder, installing dependencies from Node Package Manager (npm), and then starting the application.

    cd servernpm installnpm start
  13. The API automatically opens a browser window to verify that it returns an array of product documents.

  14. Close the extra browser tab/window. Then, close the terminal.

Deploy the MERN application to Azure App Service

Prove that the application works end-to-end by deploying the service and client to Azure App Service. Use secrets in the web apps to store environment variables with credentials and API endpoints.

  1. Within your integrated development environment (IDE), open a new terminal.

  2. Create a shell variable for the name of the preexisting resource group namedresourceGroupName.

    # Variable for resource group nameresourceGroupName="<existing-resource-group>"
  3. Create shell variables for the two web app namedserverAppName andclientAppName.

    # Variable for randomnly generated suffixlet suffix=$RANDOM*$RANDOM# Variable for web app names with a randomnly generated suffixserverAppName="server-app-$suffix"clientAppName="client-app-$suffix"
  4. If you haven't already, sign in to the Azure CLI using theaz login --use-device-code command.

  5. Change the current working directory to theserver/ path.

    cd server
  6. Create a new web app for the server component of the MERN application withaz webapp up.

    az webapp up \    --resource-group $resourceGroupName \    --name $serverAppName \    --sku F1 \    --runtime "NODE|18-lts"
  7. Create a new connection string setting for the server web app namedCONNECTION_STRING withaz webapp config connection-string set. Use the same value for the connection string you used with the MongoDB shell and.env file earlier in this tutorial.

    az webapp config connection-string set \    --resource-group $resourceGroupName \    --name $serverAppName \    --connection-string-type custom \    --settings "CONNECTION_STRING=<mongodb-connection-string>"
  8. Get the URI for the server web app withaz webapp show and store it in a shell variable name dserverUri.

    serverUri=$(az webapp show \    --resource-group $resourceGroupName \    --name $serverAppName \    --query hostNames[0] \    --output tsv)
  9. Use theopen-cli package and command from NuGet withnpx to open a browser window using the URI for the server web app. Validate that the server app is returning your JSON array data from the cluster.

    npx open-cli "https://$serverUri/products" --yes

    Tip

    Sometimes deployments can finish asynchronously. If you aren't seeing what you expect, wait another minute and refresh your browser window.

  10. Change the working directory to theclient/ path.

    cd ../client
  11. Create a new web app for the client component of the MERN application withaz webapp up.

    az webapp up \    --resource-group $resourceGroupName \    --name $clientAppName \    --sku F1 \    --runtime "NODE|18-lts"
  12. Create a new app setting for the client web app namedREACT_APP_API_ENDPOINT withaz webapp config appsettings set. Use the server API endpoint stored in theserverUri shell variable.

    az webapp config appsettings set \    --resource-group $resourceGroupName \    --name $clientAppName \    --settings "REACT_APP_API_ENDPOINT=https://$serverUri"
  13. Get the URI for the client web app withaz webapp show and store it in a shell variable name dclientUri.

    clientUri=$(az webapp show \    --resource-group $resourceGroupName \    --name $clientAppName \    --query hostNames[0] \    --output tsv)
  14. Use theopen-cli package and command from NuGet withnpx to open a browser window using the URI for the client web app. Validate that the client app is rendering data from the server app's API.

    npx open-cli "https://$clientUri" --yes

    Tip

    Sometimes deployments can finish asynchronously. If you aren't seeing what you expect, wait another minute and refresh your browser window.

  15. Close the terminal.

Clean up resources

When you're working in your own subscription, at the end of a project, it's a good idea to remove the resources that you no longer need. Resources left running can cost you money. You can delete resources individually or delete the resource group to delete the entire set of resources.

  1. To delete the entire resource group, useaz group delete.

    az group delete \    --name $resourceGroupName \    --yes
  2. Validate that the resource group is deleted usingaz group list.

    az group list

Clean up dev environment

You might also wish to clean up your development environment or return it to its typical state.

Deleting the GitHub Codespaces environment ensures that you can maximize the amount of free per-core hours entitlement you get for your account.

  1. Sign into the GitHub Codespaces dashboard (https://github.com/codespaces).

  2. Locate your currently running development container sourced from theazure-samples/msdocs-azure-cosmos-db-mongodb-mern-web-app GitHub repository.

    Screenshot of all the running devcontainers including their status and templates.

  3. Open the context menu for the codespace and then selectDelete.

    Screenshot of the context menu for a single codespace with the delete option highlighted.

Next step


Feedback

Was this page helpful?

YesNoNo

Need help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Suggest a fix?

  • Last updated on

In this article

Was this page helpful?

YesNo
NoNeed help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Suggest a fix?