Breaking News: Grepper is joining You.com. Read the official announcement!
Check it out

High level overview of Steps to make a MERN stack app(CRUD) - PART 3 

Chapter 3 - MongoDB Atlas & Mongoose


1) Go to https://www.mongodb.com/atlas/database 

2) Create an account (in case if you haven't already) then click on button Build a Database choose Free option(or any other) & create. Choose aws as Cloud provider & Region. In Cluster Name Give a name to cluster & Click Create Cluster button at bottom(let it complete).

3) In SECURITY-> Quickstart-> Username and Password- Create a new user(After Creating it can be accessed from SECURITY->Database Access) if you don't have one and also Add Current IP Address in SECURITY->Network Access.

4) Go to DEPLOYMENT->Database , you will see your cluster here in this we will create various collections corresponding to .js files in backend->routes folder like reddit.js

5) To connect our backend to created cluster(database)- click Connect->Connect your application & Copy Your Connection string and click close.

6) Go in your backend dir. go to .env file & create a new variable in it for connection string MONGO , also put your own password in place of <password> in string.

NOTE - ABOVE CONNECTION STRING IS EDITED USE YOUR OWN STRING DON'T COPY FROM HERE

7) In Terminal Git Bash while in dir.- .../backend install mongoose- npm i mongoose , mongoose basically connects backend to our database.

8) Go to server.js and using require import mongoose in variable mongoose and use mongoose.connect(process.env.MONGO).then(()=>{}).catch((error)=>{}) (It's Asynchronous hence returns a Promise after connecting to database so we use then & catch) to establish connection ( see the last part of code below to see mongoose.connect in action)

NOTE- we pass the connection string from earlier to mongoose.connect but to get res from database/establish connection it takes some time hence it's async in nature(also in case if you write MANGO instead of MONGO in process.env.MONGO or write your password wrong in connection str then it will throw an error that we .catch() and print to console) the callback function in .then() executes after connection is established, NOW THINK - SHOULD WE START LISTENING TO REQUESTS ON SERVER BEFORE OR AFTER CONNECTION IS ESTABLISHED? AFTER Ofcourse..... HENCE WE PUT our app.listen() from earlier inside the callback function of .then(). 

ALSO note that in terminal it might ask you to add a line just above mongoose.connect - mongoose.set('strictQuery', true) - Basically if second argument is true that means strict schemas & if it's false => non-strict schemas.


..... To be cont. in PART 4

X

Continue with Google

By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.