Tutorial
MongoDB & Mongoose

Connect Backend to Database || MongoDB & Mongoose

Connect Backend to Database

▶️ Setup MongoDB

  1. Go to the MongoDB website https://cloud.mongodb.com/ (opens in a new tab)

  2. Follow the steps which are shown in the video below to create a cluster and connect to it.

You can also decrease the speed of the video to 0.5x or 0.25x to understand the video better.

▶️ Create a Database

If you have a project with a database already, then make another project and then create a database in that project. Click on the build database button and then click on the Create Database button.

  1. Name the database(cluster) xamtrack and then click on the Create Database button.

Make sure you choose Shared (the free one) and not Serverless (the paid one).

  1. Click on the Create button.
  2. Give an Username and Password and then click on the Create User button.
  3. Go down and click on the Add my current IP address button and then click on the Finish and Close button.
  4. Go to Database you will see the database you created.
  5. Go to Database Access and make sure you see readWriteAnyDatabase@admin under the Roles column.

▶️ Connect Database

  1. Go to Database (left side) and then click on the Connect button.
  2. Click on the Connect your application button.
  3. You have to add your own password
  1. Go to main directory so use cd .. .
  2. Create a folder by using mkdir db .
  3. Go to the db folder by using cd db .
  4. Create a file by using echo > connect.js .
  5. Now go back to the main directory by using cd .. .
  6. Now again hit npm run dev .

💡 Setup Mongoose

  1. Now type npm i mongoose .
  2. Go to db folder and then open connect.js file.
  3. Now first import mongoose by using const mongoose = require('mongoose'); .
  4. Then create a function by using const connectDB .. .
db/connect.js
 
const connectDB = () => {
 
return mongoose.connect('uri' , options);
 
};
  • connect is the method of mongoose which is used to connect to the database.
  1. We have to create uri first so copy the uri from the connect your application button and paste it in the uri parameter.
db/connect.js
 
uri = "mongodb+srv://ser:xam:xam789.xknpt1w.mongodb.net/xamtrack?retryWrites=true&w=majority"

make sure you replace ser:xam:xam789 with your own username and password and xamtrack with your own database name between the / and ? .

  1. Now in option section add useNewUrlParser: true and useUnifiedTopology: true .
db/connect.js
 
const connectDB = () => {
    return mongoose.connect(uri,
    {
        useNewUrlParser: true,
        useUnifiedTopology: true
    });
};
 

Make sure passing the string uri instead of the variable uri to the mongoose.connect function. This is why you can get the invalid scheme error.

  • useNewUrlParser is used to parse the url.
  • useUnifiedTopology is used to use the new server discovery and monitoring engine.
  1. Now export the function by using module.exports = connectDB; .

💡 Connect to Database

  1. Go to app.js file.
  2. First import the function by using const connectDB = require('./db/connect'); .

This will return a promise so we have to use async and await .

  1. We were using async function so now we have to use await before the function.
app.js
 
await connectDB();

This will go to the connect.js file and then execute the function.

💡 Checking Connection

  1. Now go to the connect.js file.
  2. Now we have to check if the connection is successful or not.
  3. So add console.log("Database Connected") in the function.
db/connect.js
 
const connectDB = () => {
    console.log("Connecting to DB");
    return mongoose.connect(uri,
    {
        useNewUrlParser: true,
        useUnifiedTopology: true
    });
};