Youtube channel !

Be sure to visit my youtube channel

Monday, November 25, 2019

Using MongoDB Atlas Database as a Service

Atlas is an example of a Database as a service that is located in cloud space and is being offered from MongoDB. Let's see how we can use its functionality.

Note: if you want to explore more REST APIs you might find this course interesting: Learn Node.js, Express and MongoDB + JWT


Setup an Atlas account
First will create a free account inside the MongoDB Atlas. We will then login and create our first cluster from -> build a new cluster. Inside a cluster you can have lots of databases and their replicas that serve as their backup in case of failures as well as can be located in multiple places thus allow easier scaling of the database.
Choose the available clusters marked with a free tier. Click on the Security tab and then on the Add New User button. From there create a user with a password, providing read and write permissions to any database. Then we need to whitelist our IP address in order to connect to the cluster. If you don't know your external IP address for development purposes you can just type 0.0.0.0 to allow connections to Atlas from everywhere or click on the Button Add the current IP address to whitelist your IP address.
Next, we will click on the Connect button, which will reveal to us the different ways to connect to the Atlas cluster. Choose Connect to your Application. From then choose Short SRV connection string. You can now copy the revealed SRV address.

Connect to Atlas
Installing packages
1. Install npm and node from nodesource repository: https://github.com/nodesource/distributions
2. Create an empty project directory and inside type npm init -> to initialize our project (type in your name, the description of the project and other details you prefer)
// 3. Install the CORS package - to be able to make requests without cross-origin restrictions: npm install cors. You can open package.json and see the cors package listed inside the dependencies section.
// 4. Install express - to be able to create and run a local API server
5. Install mongoose - for the connection to Atlas: npm install mongoose
// 6. install body-parser to be able to work with specific parts from the body of the HTTP request: npm install body-parser

Setup of authentication configuration keys
modify package.json file to use:
"scripts": { 

 // "start:dev": "./node_modules/.bin/nodemon server.js",
 "start:prod": "NODE_ENV=prod node server.js", 
}
The second line says that we will be setting a production environment, while starting our main server.js file , and will be able to start our app with npm start:prod .

Then create keys.js file with:
if (process.env.NODE_ENV == 'production'){
module.exports = require(__dirname__+ '/keys_prod');
}else{
module.exports = require(__dirname__+ '/keys_dev');
}
We basically load up two files based on what kind of environment we are using (production or development). Then create and inside of keys_prod.js file place the connection string you've got from the Atlas website above.
Replace with your Atlas user password.
Grab the first cluster information and place it inside of mongoURI key like so:
mongoURI: 'mongodb://user:password@cluster0-shard-00....'
The other parameters nest inside mongoCFG key:
mongoCFG:{
useNewUrlParser:true,
ssl:true,
replicaSet:'Cluster0-shard-0',
authsource:'admin',
retryWrites:true
}

The API server
It will be used to respond to requests and connect to Atlas. Create server.js file and inside fill in the following information:
// initially we require the already installed packages
//const cors  = require('cors');
//const express = require('express');
const mongoose  = require('mongoose');
//const bodyParser  = require('body-parser');

// get the connection parameters
const config = require(__dirname__+'/config/keys');
// create new express application server
var app = express();
//connect to MongoDB atlas using mongoose and our connection configuration
mongoose.connect(config.mongoURI,config.mongoCFG).catch((error)=>console.log(JSON.stringify(error)));

Run the code with:
npm start:prod
// node /server.js
You should see that you are connected to the remote Atlas DB server!


// To test the express API endpoints you can use Postman, you will also need to create a postman account.
// Download the application, choosing your OS platform. Then for Ubuntu just type:
// tar -zxvf postman.....tar.gz
// then enter inside the newly created directory Postman, then run ./Postman

Congratulations!

Subscribe To My Channel for updates

Integrating AI code helpers into Visual Studio Code

In this guide, we’ll walk through setting up a local AI-powered coding assistant within Visual Studio Code (VS Code). By leveraging tools s...