Connecting Cosmos DB with the Node.js app

The design of Cosmos DB is done in such a way that you can easily integrate it with your app without doing much extra work. I mean, you don't need to do the configuration and management part, which is a huge pain with these NoSQL databases; you can easily connect to the Cosmos DB MongoDB using the existing Node.js modules you are aware of.

We are going to use the same set of node modules that we use for the normal development with MongoDB, no extra stuff!

Let's prove this point by configuring the existing project written in Node.js and MongoDB with our Cosmos DB Mongo API.

For a demonstration, we are going to use a sample code hosted as an open source:

https://github.com/prashanthmadi/mean

Let's do it:

  1. First things first, download the code. You can either use git or just visit the GitHub repository and download it as a ZIP. I am going to use git now.
  2. Run this command in the Terminal to download the project:
git clone https://github.com/prashanthmadi/mean  
  1. Once the project is downloaded, run this command to install the required dependencies:
cd mean && npm install
  1. It will install the dependencies required for the project to run. Refer to the following screenshot for reference:

Once the code is downloaded, we need to do few changes in order to run it.

  1. First, copy the MongoDB URI. Go to the Connection String screen and copy the Connection String. Refer to the following screenshot for reference:
  1. Now, go to the project folder and edit the configuration file. Open up config/env/local-development.js and change the connection URI:
module.exports = { 
  db: { 
    uri: '===== paste your URL here =====' 
  }, 
  sessionSecret: process.env.SESSION_SECRET || 'youshouldchangethistosomethingsecret', 
  facebook: { 
    clientID: process.env.FACEBOOK_ID || 'APP_ID', 
    clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', 
    callbackURL: '/api/auth/facebook/callback' 
  } 
};
  1. Save the changes in the configuration file and run the code base using the following command:
npm start  
  1. This will run the build and, once the project is started, you can view the project at localhost:3000. Refer to the following screenshot for reference:
  1. Here is how it's going to look in the browser:

Congratulations! Our app is up. But we need to do some operation in order to generate data for the MongoDB. Let's create a new account and see how it works!

  1. Click on Sign Up and fill in those details. Once your account is created, you can log in to the system, view and edit your profile, and stuff like that. You should see something like this:

We have now connected our Node app to MongoDB, so it's time to see the data inside Cosmos DB data explorer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.222.239