Authentication with Nodejs and mongoDB - Part 1
Tags: node, mongodb, database, tutorial
Published: 2020-09-13 12:23:24

It is usually easy to learn a language and forget about authentication until later. Then you realize you have missed some important steps. That was my case.

This tutorial is just the beginning of an authentication series. During the course of this series, we will be learning about tools like ``nodejs``, ``bcrypt``, ``jsonwebtoken``, ``mongoDB`` and ``React``. Let's start by getting the starter code.

<a name="1"></a>
## Starter Code
* Please clone the started code [here](https://github.com/EBEREGIT/auth-backend/tree/starter-code).

```javascript

$ git clone -b starter-code https://github.com/EBEREGIT/auth-backend

```
* In the project directory, run ``npm install`` to install all dependecies necessary
* Run ``nodemon index`` to serve the project on port 3000. Check ``http://localhost:3000/`` on you browser to comfirm


## Database Setup
In this part, we will be covering the database setup and we are using [mongoDB atlas](https://www.mongodb.com/cloud/atlas). 

Proceed to the [website](https://account.mongodb.com/account/register) and create a free account

### Create New Database User
* On your dashboard, click on the ``Database Access`` link by the left. *(That will prompt you to Add a new database user)*.

![Database Access photo](https://dev-to-uploads.s3.amazonaws.com/i/j3jakvaahhes3hwifuyw.JPG)

* Click on the button. *(``Add New Database User`` dialogue box opens)*

![Add New Database User dialogue box](https://dev-to-uploads.s3.amazonaws.com/i/3y63tqp3ama824jyjagg.JPG)

* Select ``Password`` as Authentication Method

* Type in a username of your choice

* Type in a password or Autogenerate Secure Password. *(I advice you auto generate a password and store it somewhere. You will need it soon)*

* Click on ``Add User`` to complete the process.

![User Created](https://dev-to-uploads.s3.amazonaws.com/i/iv92tdfrqegxgnj1lwyz.JPG)

### Create a Cluster
* On the side links, click on ``clusters``. *(this brings you to the cluster page with a button: ``Build a Cluster``)*

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/s2mtfzhyrzkz79omckha.JPG)

* Click the button. *(Another pages comes up)*

* Choose the ``free cluster``. *(The settings page opens up. We will not be making any changes on this page)*

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zmitdioyw4io3vuuv7u2.JPG)

* Click ``Create Cluster`` *(Wait a while for the cluster to be created completely. Once it is done, your screen should be like mine below)*

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/whgefzv95dnmy2qo91xn.JPG)

### Connect User to Cluster
* Click on the ``connect`` button

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/n92cm0ztfc55i66vwx8t.JPG)

* In the ``Connect to Cluster0`` modal that comes up, select ``Connect from Anywhere`` and update the settings

* Click on the ``Choose a connection method`` button

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/y42t9m2kzmkp3oon0bb7.JPG)

* Click on ``Connect Your Application``. *(In the page that opens, ensure that the ``DRIVER`` is ``nodejs`` and the ``VERSION`` is ``3.6 or later``)*

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/9yrg7nknor2xhogwldoe.JPG)

* Copy the connection string and store somewhere. You will need it soon. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/jj816egjtx7jjsiixs1a.JPG)

It should be similar to mine

```javascript

mongodb+srv://plenty:<password>@cluster0.z3yuu.mongodb.net/<dbname>?retryWrites=true&w=majority

```

* Close the dialogue box

### Create a Collection (Tables)
* Back in the Cluster page, click on ``COLLECTIONS``

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/gtk0xqwbcf7xgdef6d9p.JPG)

* You should be in this page below. Click on the ``Add My Own Data`` button

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/b3itcf0383pvcuk7f8g7.JPG)

* In the dialogue box that comes up, enter a ``database name`` and a ``collection name``. *(My Database Name is ``authDB`` and My Collection name is ``users``)*

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/2bb2p5fm1kz3muma35ow.JPG)

* Click the ``Create`` button

*Congratulations on creating that Database and collection (table) like mine below*

## Connect Nodejs to MongoDB
* Let's get back to our [starter Code](#1)

* Still remember the database name, connection string and password you generated? We will put them to use in a moment

* Replace the ``<password>`` and ``<dbname>`` with the password you generated and the database name you created like so

```javascript

mongodb+srv://plenty:RvUsNHBHpETniC3l@cluster0.z3yuu.mongodb.net/authDB?retryWrites=true&w=majority

```

* Create a file in the root folder and name it ``.env``

*Don't know about ``.env``? Checkout this article*

* Create a variable ``DB_URL`` and assign the connection string to it like so

```javascript

DB_URL=mongodb+srv://plenty:RvUsNHBHpETniC3l@cluster0.z3yuu.mongodb.net/authDB?retryWrites=true&w=majority

```

* create a folder and name it ``db``

* Create a new file in it and name it ``dbConnect.js``

* Install [mongoose](https://www.npmjs.com/package/mongoose)

```javascript

npm i mongoose -s

```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/lsyp8s6sk30ke7g8x0ym.JPG)

* In the ``dbConnect`` file, require ``mongoose`` and ``env`` with the following code

```javascript

// external imports
const mongoose = require("mongoose");
require('dotenv').config()

```

* Create and export a function to house our connection like so

```javascript

async function dbConnect() {

}

module.exports = dbConnect;

```

* In the function, try to connect to the database we created using the connection string from the ``.evn`` file


```javascript

// use mongoose to connect this app to our database on mongoDB using the DB_URL (connection string)
  mongoose
    .connect(
        process.env.DB_URL,
      {
        //   these are options to ensure that the connection is done properly
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useCreateIndex: true,
      }
    )

```

* Use a ``then...catch...`` block to show if the connection was successful or not like so

```javascript

.then(() => {
      console.log("Successfully connected to MongoDB Atlas!");
    })
    .catch((error) => {
      console.log("Unable to connect to MongoDB Atlas!");
      console.error(error);
    });

```

*The ``dbConnect`` file should look like this:*

```javascript

// external imports
const mongoose = require("mongoose");
require('dotenv').config()

async function dbConnect() {
  // use mongoose to connect this app to our database on mongoDB using the DB_URL (connection string)
  mongoose
    .connect(
        process.env.DB_URL,
      {
        //   these are options to ensure that the connection is done properly
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useCreateIndex: true,
      }
    )
    .then(() => {
      console.log("Successfully connected to MongoDB Atlas!");
    })
    .catch((error) => {
      console.log("Unable to connect to MongoDB Atlas!");
      console.error(error);
    });
}

module.exports = dbConnect;

```

* In the ``app.js`` file, require the dbConnect function and execute it like so

```javascript

// require database connection 
const dbConnect = require("./db/dbConnect");

// execute database connection 
dbConnect();

```

* Check your terminal. If you didn't miss any step, you should have ``"Successfully connected to MongoDB Atlas!"`` printed. See mine below

![Terminal showing "Successfully connected to MongoDB Atlas!"](https://dev-to-uploads.s3.amazonaws.com/i/u36z3xyjtr6mpgyq6gty.JPG)

### Conclusion 
In this article, we have been able to see how to easily connect our nodejs app to our database on mongoDB.

All codes are [here](https://github.com/EBEREGIT/auth-backend/tree/db-config)

{% github eberegit/auth-backend no-readme %}

In the next article, we will look at [creating model for the user and registering a user](https://dev.to/ebereplenty/authentication-with-nodejs-and-mongodb-part-2-1hg9)