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 installto install all dependecies necessary - Run
nodemon indexto serve the project on port 3000. Checkhttp://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 Accesslink by the left. (That will prompt you to Add a new database user).
- Click on the button. (
Add New Database Userdialogue box opens)
Select
Passwordas Authentication MethodType 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 Userto complete the process.
Create a Cluster
- On the side links, click on
clusters. (this brings you to the cluster page with a button:Build a Cluster)
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)
- Click
Create Cluster(Wait a while for the cluster to be created completely. Once it is done, your screen should be like mine below)
Connect User to Cluster
- Click on the
connectbutton
In the
Connect to Cluster0modal that comes up, selectConnect from Anywhereand update the settingsClick on the
Choose a connection methodbutton
- Click on
Connect Your Application. (In the page that opens, ensure that theDRIVERisnodejsand theVERSIONis3.6 or later)
- Copy the connection string and store somewhere. You will need it soon.
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
- You should be in this page below. Click on the
Add My Own Databutton
- In the dialogue box that comes up, enter a
database nameand acollection name. (My Database Name isauthDBand My Collection name isusers)
- Click the
Createbutton
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_URLand 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
dbCreate a new file in it and name it
dbConnect.jsInstall mongoose
npm i mongoose -s
- In the
dbConnectfile, requiremongooseandenvwith 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
.evnfile
// 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.jsfile, 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
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
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
Top comments (2)
This article was very helpful. There was no way I could go wrong. Deployed on Heroku for the first time and it was seamless because of this. Thank you!!
Wow... I am delighted to have been of help. Thank you.