Build A MERN Stack App in 5 Days (Day 1: Setting up the backend)

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 …

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

Models

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

AModel

Routes

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

And in AnswerRoutes.js :

Aroutes

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

Allroutes

Connect to MongoDB

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

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

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

cluster

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

env

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

Putting it all together

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

In the final step, we need to add a ‘start’ script in our package.json:
package

Now, go ahead and type ‘npm start’ in the terminal to start our server and if everything is done right, we should see:
start

Additional | Testing with Postman

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

populate

Conclusion

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

Homework

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
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!


Print Share Comment Cite Upload Translate
APA
rohanjsx | Sciencx (2024-03-29T15:33:00+00:00) » Build A MERN Stack App in 5 Days (Day 1: Setting up the backend). Retrieved from https://www.scien.cx/2022/03/26/build-a-mern-stack-app-in-5-days-day-1-setting-up-the-backend/.
MLA
" » Build A MERN Stack App in 5 Days (Day 1: Setting up the backend)." rohanjsx | Sciencx - Saturday March 26, 2022, https://www.scien.cx/2022/03/26/build-a-mern-stack-app-in-5-days-day-1-setting-up-the-backend/
HARVARD
rohanjsx | Sciencx Saturday March 26, 2022 » Build A MERN Stack App in 5 Days (Day 1: Setting up the backend)., viewed 2024-03-29T15:33:00+00:00,<https://www.scien.cx/2022/03/26/build-a-mern-stack-app-in-5-days-day-1-setting-up-the-backend/>
VANCOUVER
rohanjsx | Sciencx - » Build A MERN Stack App in 5 Days (Day 1: Setting up the backend). [Internet]. [Accessed 2024-03-29T15:33:00+00:00]. Available from: https://www.scien.cx/2022/03/26/build-a-mern-stack-app-in-5-days-day-1-setting-up-the-backend/
CHICAGO
" » Build A MERN Stack App in 5 Days (Day 1: Setting up the backend)." rohanjsx | Sciencx - Accessed 2024-03-29T15:33:00+00:00. https://www.scien.cx/2022/03/26/build-a-mern-stack-app-in-5-days-day-1-setting-up-the-backend/
IEEE
" » Build A MERN Stack App in 5 Days (Day 1: Setting up the backend)." rohanjsx | Sciencx [Online]. Available: https://www.scien.cx/2022/03/26/build-a-mern-stack-app-in-5-days-day-1-setting-up-the-backend/. [Accessed: 2024-03-29T15:33:00+00:00]
rf:citation
» Build A MERN Stack App in 5 Days (Day 1: Setting up the backend) | rohanjsx | Sciencx | https://www.scien.cx/2022/03/26/build-a-mern-stack-app-in-5-days-day-1-setting-up-the-backend/ | 2024-03-29T15:33:00+00:00
https://github.com/addpipe/simple-recorderjs-demo