DEV Community

loading...

Connecting to MongoDb cloud (Atlas)

willemdt369 profile image WillemDT369 ・5 min read

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

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

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

Alt Text

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

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

Alt Text

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

Alt Text

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

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

Alt Text

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

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

Alt Text

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

Alt Text

Alt Text

Now you should see something like this.

Alt Text

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

Next we add some commands in the terminal for creating the package-lock.json file

npm init -y
Enter fullscreen mode Exit fullscreen mode

and installing the packages.

npm i nodemon express mongoose
Enter fullscreen mode Exit fullscreen mode

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

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

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}`);
});
Enter fullscreen mode Exit fullscreen mode

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

Alt Text

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

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

Alt Text

Alt Text

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

Alt Text

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

Alt Text

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

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;
Enter fullscreen mode Exit fullscreen mode

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

const InitiateMongoServer = require("./db");

InitiateMongoServer();
Enter fullscreen mode Exit fullscreen mode

Now the updated index.js file looks like this.

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}`);
});
Enter fullscreen mode Exit fullscreen mode

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

Alt Text

You are now connected to you MongoDb cloud

Discussion (0)

Forem Open with the Forem app