Connecting to MongoDB with Mongoose

During the starting days of my journey into back-end programming, I had taken too much information right in the beginning. Although it's good to have plenty of resources but at times too much information right in the beginning this can be overwhelming !

Especially while connecting my app to mongoDB, I used to look out for pieces that would give me an overview of how it all inter connected behind the scenes. I did find some amazing pieces on many websites, but not exactly how I wanted it, hence after finally learning it I decided to write my own.

Enough with the small talks, Let's express our way into mongoDB on a mongoose !

Setting up your mongoDB Atlas account :

  • Step 2: Set up your account with the basic details:
  • Step 3: Select the "Free Database" , this is enough for your basic projects or even a company in the start up phase.
  • Step 4: Create a cluster selecting your nearest tier, and keep the other settings as they are.
  • Step 5: Create a local user to connect to the database, keep the credentials somewhere safe, as they will help you to connect you to connect to the database.
  • Step 6: Wait for the cluster to be created
  • Step 7: Click on connect once the cluster is set up.
  • Step 8: Connect using MongoDB Compass
  • Step 9: Download the mongoDB Compass if you don't have it set up already and copy the connection string being shown in your account.
  • Step 10: Copy the connection string into mongoDB Compass and replace the line with "" with the password you created in Step 5 and click "Connect"
  • Step 11: Once you see this after clicking connect, your atlas cloud DB is now successfully set up!

Connecting to the DB using node

  • Step 1: Open a new repl on replit.com with NodeJS
  • Step 2: Click on examples after your repl it created
  • Step 3: Select the example for express app from the fields.
  • Step 4: The express app is now set up, let us now proceed with the connection to our database.
  • Step 5: Add mongoose as dependency in your app from packages tab in the left:
  • Step 6: Click the connect button to get the URI to connect to your database with your node app
  • Step 6: Select the URI from your database which is used to connect to the app
  • Note : Make sure that connections are allowed from everywhere (all IPs), to do this go to the Network Access tab in the left and edit the settings.
  • Step 7: Use the following code to connect to your database:
mongoose.connect('<your-URI-here>', {useNewUrlParser: true, useUnifiedTopology: true}).then(()=>console.log("connected !!")).catch(error=>console.error("mongoose connection failed...", error))

You are now connected to your mongoDB Atlas database using mongoose from your node app !

You can refer to the following repl for the exact code :
https://replit.com/@ShasheeshPuroh1/mongoDB#index.js

22