Create your MERN App- Part 1 (Backend)

What does MERN mean?
M- Mongo Db,E- ExpressJS,R- ReactJS,N- NodeJS

This article will help you to create Backend consist of Mongo, NodeJS and ExpressJS and Frontend with ReactJS. In this part 1 , you will be able to create backend and follow the part 2 to create the frontend. This will be quick recap to create a MERN app.

Let’s first create our Backend.

Backend basically means the server side of the web application. I hope you already created a folder for the project or create the empty folder and open the Visual Code.Within your project folder. First, you need to create package.json. For this you can either go with yarn or npm.

yarn init | npm init

So now you should have created the package.json file.Now we need some dependencies to create the server side.

npm install body-parser cors mongoose nodemon express

Let’s see why we need this to our server.

Express- Server Framework.

Body-Parser- To handle body requests in network . Ex: req.body.

Nodemon/node- Nodemon to restart your server, whenever there is a change. Node can be used, but it won’t restart your server automatically. Better to use nodemon.

Cors- CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options. (https://www.npmjs.com/package/cors)

Mongo- Database models dealing with our system.

Now you will be able to see node_modules files under your directory. Hoorey you can check the dependencies you have installed there.

Let’s now create our NodeJS file to run the server. It is very much easier.Create a file called index.js.

const express = require('express');const bodyParser = require('body-parser');const cors = require('cors');const app = express();const portNumber = 5000;app.use(bodyParser.urlencoded({ extended: true }))app.use(cors());app.use(bodyParser.json());
app.get('/', (req, res) => {res.send('Hello World!');});app.listen(portNumber, () => console.log(`Running on ${portNumber}`));

Paste the above code above and type the below mentioned command.

nodemon index.js

Your server started and running on port number 5000

We have successfully started our server. You can check in your browser too.

http://localhost:5000/

You will be able to see Hello World.

Let’s connect the MongoDB now.You need to install mongoose dependency first.

npm install mongoose or yarn add mongoose

I’m going to use MongoDb Atlas. https://account.mongodb.com/account/login. You can create your account here. After login it will ask to create an organisation. You can create your organsation as well. Now you can able to see a button called New Project in the right side top. Create your new project by giving the details. After successfully creating the Project, you will be redirected to clusters.

Click on the build Cluster. You can select the third option. It is free to use. In the next page, let all the fields be default. Down below you can see create cluster. Yah that’s all you have created the cluster. (If you cannot able to create the cluster free. It is better to check the free regions.)

It will take some time to create your cluster.

Click on the connect under Cluster0. A modal will pop out.

A . Setup connection security

  1. Add your IP Address.
  2. Create a Database User. (remember your username and password)
  3. Create

B. Choose a connection method

  1. Driver NodeJS, version 3.6 later

You will be able to see connection string.

mongodb+srv://dbuser:<password>@cluster0.ifgcf.mongodb.net/<dbname>?retryWrites=true&w=majority

Replace the password you mentioned in the first step and replace <dbname> with your database name.
Example-
Username :- dbuser ,
Password-test

Your connection string will look like this with password.

mongodb+srv://dbuser:test@cluster0.ifgcf.mongodb.net/dbuser?retryWrites=true&w=majority

Copy the connection string. And move back to the index.js file.Now we need to add mongoose. We already installed mongoose dependency.

Add the following in the index.js,

const mongoose = require("mongoose");

Replace the connection string and paste on the index.js

mongoose.connect('mongodb+srv://dbuser:test@cluster0.phmwx.mongodb.net/dbuser?retryWrites=true&w=majority',{useNewUrlParser:true,useCreateIndex: true,useUnifiedTopology: true,},(err)=>{if(!err){console.log('Mongo Connected ');}else {console.log('Not Connected');}});
Index.js

Final code of index.js will look like as above.

Now you can run the server again and check whether it is working. If it is working it will shown as

Hoorey, We have connected MongoDB as well.

Before moving to the frontend , let’s create a dummy model and route to check. Create a folder called model. Under model create a file called about.js.

We are going to create about model with description attribute.Paste the below code in the about.js.

const mongoose = require(‘mongoose’);const Schema = mongoose.Schema;const AboutSchema = new Schema({  description: { type: String, required: true }}, {timestamps: true,});const Aboutus = mongoose.model(‘Aboutus’, AboutSchema);module.exports = Aboutus;

After creating the model we need to create a route for it. For that we need to create route folder and within that create a file called aboutRoute.js.

Your folder structure will look like this now

In the route we are going to create API for about. First we need to add the router and model path to the route.I have given the path according to my file structure. You should change according to your structure.

const router = require(‘express’).Router();const path = require(‘path’);let About = require(‘../modal/about’);

After adding we are going to create POST call for about model.

router.route(‘/add’).post((req, res) => {const description = req.body.description;const newAbout= new About({description});newAbout.save().then(() => res.json(‘About added!’)).catch(err => res.status(400).json(‘Error: ‘ + err));});module.exports = router;

After creating API for the about , now we need to call the router from server. And create a API endpoint for this particular model.

var about = require(‘./routes/about’);app.use(‘/api/about’, about);

In the POSTMAN or INSOMNIA you can check whether the API is working or not.Endpoint for about model- api/about and for the post call we have to call
api/about/add

Create a new request for post call. Like below,

As we can see our API is working. You can go to mongo cluster and check whether new collection has been created with the newly entered detail.

Finally we are done with Backend. Now we can move to FrontEnd.

I’m an undergraduate student from SLIIT.Currently following 4th Year First Semester.