Build A MERN Stack App in 5 Days (Day 1: Setting up the backend)
Tags: react, webdev, mongodb, javascript
Published: 2022-03-26 04:59:20

Hello! Welcome to part 1 of the series.. Today, we will:
- set up our backend 
- connect to MongoDB
- create Models
- create Routes & their functions (controllers)

Prerequisites: Basic knowledge of Express & MongoDB

Before we get to coding, let's plan out our models so that we are all on the same page. The two main models for our application will be: **Questions** and **Answers**. 

Every **Question** will have a:
- description
- imageURL (optional)
- answers
- createdAt
- user (the user who submitted the question)

Every **Answer** will have a:
- answer (the actual answer submitted by the user)
- questionID (id of the question it is answering)
- createdAt
- user (the user who submitted the answer)

Okay, so let's start coding!
We will have two separate folders: *client* & *server* . The 'client' folder will contain our frontend code and the 'server' folder will include our backend code. Today, we will be working in the server directory so make sure you are in the correct directory! Once we are in the server directory, we'll need to initialize our package.json with *npm init* and install the dependencies. Our dependencies will be:
- **Express**: Our server framework 
- **Mongoose** : To communicate with our MongoDB database
- **CORS**: Middleware used to enable CORS with various options.
- **BodyParser**: Middleware for parsing incoming request bodies.
- **Dotenv**: To load our environment variables in development.

So, go ahead in your terminal once you are in the server directory

![Init](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q6ublplqjv5p9empu0ec.png)

<h3> Models </h3>
Let's go ahead and code our Models! Create a separate folder called 'models' in the server directory and create two separate files: QuestionModel.js and AnswerModel.js and let's go ahead and code our models as we discussed earlier.

![QModel](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5lmy5r6m7cg3su3pqvym.png)

![AModel](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h3q4mxz81t4e3eb8gjh1.png)

<h3> Routes </h3>

With our models ready, next we need to setup our routes and their controllers. For now, we will have three controllers:

- **Add Question** : triggered upon a POST request to the route '/api/questions'. Takes in the fields description, imageURL, user from the request body and adds the new question to the database.

- **Add Answer** : triggered upon a POST request to the route '/api/answers'. Takes in the fields answer, questionID, user from the request body and adds the new answer to the database.

- **Get All Questions** : triggered upon a GET request to the route '/api/questions'. Returns all the questions in the database alongwith all their answers.

So, create a new folder called 'routes' in the server directory with two files: QuestionRoutes.js & AnswerRoutes.js.. QuestionRoutes will contain Add Question & Get All Questions while AnswerRoutes will contain a single controller for now which is Add Answer. So, go ahead and in QuestionRoutes.js :

![QRoutes](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ph2k32bcpmenkj8x7igf.png)

And in AnswerRoutes.js :


![Aroutes](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qph884yzo8qfmiwnm9lr.png)

Go ahead and create an index.js file in the 'routes' folder and import all our routes:

![Allroutes](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3u8eslhyah4abyk5lxp9.png)

<h3> Connect to MongoDB </h3>
Now, with our Models & Routes set up ,let's go ahead and actually connect to our database. We will be using Cloud MongoDB Atlas for our database, so go ahead and login/register on cloud.mongodb.com and 'Add New Project' > 'Create a Database':

![createDB](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y96xmigas6te7nmfsvty.png)

The cluster provisioning takes around 3-5 minutes. In the meantime, go to the 'Database Access' tab and 'Add New Database User', after that go to the 'Network Access' and add the IP Address '0.0.0.0' to the IP Access List!

![adduser](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4jc1ll7hd1uto5erph19.png) 

Once the cluster is provisioned, click on 'Connect' > 'Connect your MongoDB application' and copy the connection string,this will be our **MongoURI**:

![cluster](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h6rshapb2anz5bsme5o0.png)

Now create a '.env' file in your the server directory and:

![env](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bzvkm8kluqah72e0q0iu.png)

*Make sure to replace the 'password' field with the password for your user and 'myFirstDatabase' with the name of your database!*

Now, go ahead and create a 'db.js' file in the 'server' directory where we will write a function to establish connection with our database.

![db](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fvh5fa9i1puun9m8vmve.png)

<h3> Putting it all together </h3>
So far, we have:
- Created our Models
- Created our Routes
- Setup MongoDB

Now, let's go ahead and put it all together for our backend, where we create an 'index.js' file which will be our main file in the server directory, where we will listen on our server, setup middlewares and connect to our database!
![Index](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1ya9da71bokqcawu9gv6.png)

In the final step, we need to add a 'start' script in our package.json:
![package](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zlosc64dewhdaztngphs.png)

Now, go ahead and type 'npm start' in the terminal to start our server and if everything is done right, we should see:
![start](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uyu1g3hx48xin1y11ofp.png)

<h3> Additional | Testing with Postman </h3>
Go ahead and test the routes with Postman or your favorite API Testing tool.. Try adding some dummy data and make sure it populates the database.

![postman](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/de5xm1xouxu6s90reohr.png)

![populate](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d95ae7hnjqieq2qbnvxt.png)

<h3> Conclusion </h3>
So today, we setup our backend, our models, routes, connected to MongoDB and started our server. Join in for part 2 where we start working on the frontend and setup React + TailwindCSS

<h4> Homework </h4>
Unlike most coding tutorials where the reader has to just copy paste the code, in this tutorial I just wanted to show the exhibit functionalities and leave ample space for the reader to add more additional assignments of their own, where the reader can improve upon the app and add functionalities of their own and learn by practice.. Some functionalities you can add:

- Create a 'Category' model or add a 'category' field to Questions and add a route to get Questions according to category.
- Make the answer route protected i.e. allow access to the route only after user is authenticated. You can use 'passport' or some other package for this.

[Code repository](https://github.com/kishibe-rohan/kysymys-tutorial)
Feel free to fork and add your own touch to the project! 
Reach out to me for any issues/queries.
See you in Part 2!