Connecting to MongoDb cloud (Atlas)
Tags: node, mongodb, beginners, atlas
Published: 2021-04-29 23:36:00

###Introduction

As a beginning web developer nearing the end of the course, I’m writing my first article. In our last project we used a local database first because we couldn’t find a proper way to use a free online mySql database. That’s why I tried MongoDb cloud (Altlas), so that’s what I’ll be talking about today.

##PART 1: Creating a MongoDB cloud database

###First things first

The first thing you need to do of course is create a mongoDb account and set it up. You can do so by going to https://www.mongodb.com/cloud/atlas and follow the steps.

**Step 1.**
Click “start free” and enter your data (I used connect with gmail). Accept the privacy and you’re good to go.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/irf2ouhmhofj5xdhtsye.png)

**Step 2.**
Now you’ll see something like the picture below. They provide some defaults which you can change of course. Don’t mind the “preferred language” section as you can change this later. Enter what you want and click “continue”.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nluu8k8ikwv5msy56ovg.png)

**Step 3.**
Next choose your cluster. I chose the shared cluster which is the free option.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f5fdoxjzfr5n951510vh.png)

**Step 4.**
Here you can choose your provider and region. I just left it how it was. Then you click “create cluster” and wait.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vp9q1lclaadrwhs75in4.png)

This brings you to your dashboard and you should see this.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g3u0tb2lae4jwl61031q.png)

And when it’s finished it should look like this.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k4ugcifbfi81m32gp8mh.png)

###Second things second

What we’ll do now is actually creating our database. Again, follow the steps and you’re good to go.

**Step 1.**
In the left sidebar go to “Database Access” and click “Add New Database User”.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i0xm7vzsxyio2zzloery.png)

**Step 2.**
Fill in a username and password and remember it because we’ll need it later on.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/59lyn4yi5c5z2khv2ake.png)

Normally this should work, but it’s possible you’ll have to change the “Database User Privileges” settings to “Grant specific privileges”. Then you click “Select Role” and choose clusterMonitor. Finally click “Add User”.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vqy3n8zijd62q5s7qk8q.png)

**Step 3.**
In the left sidebar go to “Clusters”. Than in the sandbox click “collections".

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yqy6j61lswksys4t6dev.png)

**Step 4.**
Click “Add My Own Data” enter your database name and collection name. Click “Create” and you’re done.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vwwc4kpxyhzsjugp9tz2.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/onsexq3d6zde0nn6gcr6.png)

Now you should see something like this.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l6f9d73b54gys9w8w8rn.png)


##PART 2: Making the connection

###What you need
1. An IDE like VsCode
2. Nodejs installed
3. Packages (nodemon, express, mongoose)

To begin with, we open a new folder in which we are going to build our connection. In there I made a folder "server" which contains the files db.js and index.js. So it looks like this (the package files and node modules will come next).

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kvqkfpnkfkqb4hszyhpj.png)

Next we add some commands in the terminal for creating the package-lock.json file
```
npm init -y
```
and installing the packages.
```
npm i nodemon express mongoose
```
Now your folder should look like the picture above.

We use **nodemon** for automatically restarting the server so we don't have to do it manually each time we change our file.
**Express** is used to make our API and with **mongoose** we connect to our database.

Then in the package.json file we add ```"start": "nodemon index.js"```to the scripts section. When we now do ```npm start```to run the server, nodemon will give us a help.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bvz8ziv1lcvfkhd5vym2.png)

Now we're ready for the code. First add this to the index.js file.

```js
const express = require("express"); // For making an api

const app = express();

// PORT either the one in the .env file or 4000
const PORT = process.env.PORT || 4000;

app.use(express.urlencoded({
  extended: true
}));
app.use(express.json());

app.get("/", (req, res) => {
  res.send({ message:"API Still Working Fine (-_-)!" });
});

app.listen(PORT, (req, res) => {
  console.log(`Server Started at PORT ${PORT}`);
});
```

If you enter **npm start** you should get this in your terminal.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/agway4jm8zxrxqclnmwj.png)

###TO BE CONTINUED...

###Back to your MongoDb (Atlas) Account

Go back to clusters and click "connect" left from "collections" (if you still remember).

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9sgqvvyx7p9hoi6481zw.png)

Add an IP address to give access to your database (I used "Allow access from anywhere"). And click "Choose a connection method".

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l0h5tz0tjld9jyidjf0b.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hsa84fibkg3wu0ork91f.png)

Then click "Connect your application" and you'll see this.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k4jronjmr6ezp4092pz6.png)

This is the link we need to connect to our database.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p34f9enhajrlrxymmtkx.png)


###CONTINUE

Back to our code now. In the db.js file we add the following code (don't forget to change your password and database name in the link).
This:
`mongodb+srv://Durr:<password>@cluster0.ryrer.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`

Becomes:
`mongodb+srv://Durr:example@123@cluster0.ryrer.mongodb.net/example?retryWrites=true&w=majority`

```js
const mongoose = require('mongoose');

const MONGOURI = "mongodb+srv://Durr:example@123@cluster0.ryrer.mongodb.net/example?retryWrites=true&w=majority";

const InitiateMongoServer = async () => {
    try {
        await mongoose.connect(MONGOURI, {
            useNewUrlParser: true,
            useUnifiedTopology: true
        });
        console.log("Connected to DB !!");
    } catch (e){
        console.log(e);
        throw e;
    }
};

module.exports = InitiateMongoServer;
```

All we need to do now is use the db.js file and its function in the index.js file. We do this by adding the following bits 
```js
const InitiateMongoServer = require("./db");

InitiateMongoServer();
```

Now the updated index.js file looks like this.

```js
const express = require("express"); // For making an api
const InitiateMongoServer = require("./db");

InitiateMongoServer();

const app = express();

// PORT either the one in the .env file or 4000
const PORT = process.env.PORT || 4000;

app.use(express.urlencoded({
  extended: true
}));
app.use(express.json());

app.get("/", (req, res) => {
  res.send({ message:"API Still Working Fine (-_-)!" });
});

app.listen(PORT, (req, res) => {
  console.log(`Server Started at PORT ${PORT}`);
});
```

Hit that npm start again and you should get this message in your terminal.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uqbk1k3xeeykplqnhm14.png)

**You are now connected to you MongoDb cloud**