Connect Backend to Database || MongoDB & Mongoose
▶️ Setup MongoDB
-
Go to the MongoDB website https://cloud.mongodb.com/ (opens in a new tab)
-
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.
- Name the database(cluster)
xamtrack
and then click on theCreate Database
button.
Make sure you choose
Shared
(the free one) and notServerless
(the paid one).
- Click on the
Create
button. - Give an Username and Password and then click on the
Create User
button. - Go down and click on the
Add my current IP address
button and then click on theFinish and Close
button. - Go to
Database
you will see the database you created. - Go to Database Access and make sure you see
readWriteAnyDatabase@admin
under theRoles
column.
▶️ Connect Database
- Go to Database (left side) and then click on the
Connect
button. - Click on the
Connect your application
button. - You have to add your own password
- Example: MONGO_URL = 'mongodb+srv://your-username:your-password@cluster0.your-hostname.mongodb.net/?retryWrites=true&w=majority'
- You have to replace
your-username
andyour-password
with your own username and password- In my Case : MONGO_URL = 'mongodb+srv://xam:xam789@cluster0.zvzbzec.mongodb.net/?retryWrites=true&w=majority'
- Go to main directory so use
cd ..
. - Create a folder by using
mkdir db
. - Go to the
db
folder by usingcd db
. - Create a file by using
echo > connect.js
. - Now go back to the main directory by using
cd ..
. - Now again hit
npm run dev
.
💡 Setup Mongoose
- Now type
npm i mongoose
. - Go to
db
folder and then openconnect.js
file. - Now first import mongoose by using
const mongoose = require('mongoose');
. - Then create a function by using
const connectDB ..
.
const connectDB = () => {
return mongoose.connect('uri' , options);
};
- connect is the method of mongoose which is used to connect to the database.
- We have to create uri first so copy the uri from the
connect your application
button and paste it in theuri
parameter.
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 andxamtrack
with your own database name between the/
and?
.
- Now in option section add
useNewUrlParser: true
anduseUnifiedTopology: true
.
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.
- Now export the function by using
module.exports = connectDB;
.
💡 Connect to Database
- Go to
app.js
file. - First import the function by using
const connectDB = require('./db/connect');
.
This will return a promise so we have to use
async
andawait
.
- We were using async function so now we have to use
await
before the function.
await connectDB();
This will go to the
connect.js
file and then execute the function.
💡 Checking Connection
- Now go to the
connect.js
file. - Now we have to check if the connection is successful or not.
- So add
console.log("Database Connected")
in the function.
const connectDB = () => {
console.log("Connecting to DB");
return mongoose.connect(uri,
{
useNewUrlParser: true,
useUnifiedTopology: true
});
};