loading...

Authentication with Nodejs and mongoDB - Part 1

ebereplenty profile image NJOKU SAMSON EBERE Updated on ・5 min read

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.

Starter Code

  • Please clone the started code here.

$ 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.

Proceed to the website 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

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

Add New Database User dialogue box

  • 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

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

  • 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

  • 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

Connect User to Cluster

  • Click on the connect button

Alt Text

  • 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

  • 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

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

Alt Text

It should be similar to mine


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

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

Alt Text

  • 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

  • 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

  • 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


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

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


npm i mongoose -s

Alt Text

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

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

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

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

// 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

.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:


// 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

// 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!"

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

GitHub logo EBEREGIT / auth-backend

This tutorial teaches how to create authentication for a user using nodejs and mongoDB

In the next article, we will look at creating model for the user and registering a user

Posted on by:

ebereplenty profile

NJOKU SAMSON EBERE

@ebereplenty

I love providing solutions to real world problems. When I am not coding, I enjoy movies, hanging out and working out.

Discussion

markdown guide