Introduction
In this article, we will see how to connect MongoDB in detail. Many of us will make mistakes while connecting to the database. This article will help you to set up MongoDB properly and connect to your database.
Set up MongoDB
Step 1
Open https://account.mongodb.com/account/login
Step 2
Click on login with Google.
Step 3
Enter your Email ID and click on Submit.
Step 4
Change the "Organization", "Project Name" and select one language from "What is your preferred language?". Click on Continue.
Step 5
Click on "Shared Clusters". Click on "Create a cluster".
Step 6
Choose anyone from "Cloud Provider & Region". Select relevant "Religion" and click on "Create Cluster".
Step 7
This page will be ready now. Click on "CONNECT".
Step 8
Give "Username" and "Password" and then click on "Create Database User". This will be your <dbusername> and <dbpassword>.
Step 9
Don't make any changes. Click on "Add an IP address" and then click on "Choose a connection method".
Step 10
Now click on "Close".
Step 11
Click on "COLLECTIONS".
Step 12
Click on "Add My Own Data".
Step 13
Give the "DATABASE NAME" and "COLLECTION NAME" then click on "Create".
Step 14
Click on "INSERT DOCUMENT" and add some data like this,
Step 15
Click on "Insert".
Step 16
This will be your <dbanme> and <collectionname>.
What next?? Where to get Connection URL? How to add a connection URL?
Step 1
Go to Browser. Open https://cloud.mongodb.com/v2/60cb6fd983b16a16db9f8553#clusters
Step 2
Click on "CONNECT" and click on "Connect your application".
Step 3
Copy the highlighted line and paste this line on the server.js file.
Step 4
Now update the dbusername, dbpassword, dbanme.
Step 5
Also, update this line,
collection = client.db("dbname").collection("collectionname");
// Provide your dbname and collectionname
Step 6
This is how your server.js file looks like,
Step 7
That's all. You are all set to run the application which connects backend MongoDB.
Conclusion
In this article, we have learned step-by-step procedures to set up MongoDB from the scratch. Also, we have seen how we can create a cluster, database, collection, and connect URL via server.js file which in turn communicates with MongoDB on the backend. Hope you find this article helpful. If you have any queries/concerns, please drop a comment. Happy to help. Thank you.