Why choose MERN stack?

Divyani Tyagi
Aeologic
Published in
9 min readJul 5, 2020

Although web development technologies are going through exemplary changes with time, it is also inevitable that expectations of users are aloft. Consequently, developers work hard day and night with their full efficacy to provide a website having better user experience, lesser loading time, and mobile-friendliness.
HTML, CSS, and Javascript are the cornerstone of Web development but are no longer enough to fulfill all the above demands. So now we have two technology stacks MERN and MEAN which are developer’s favorite nowadays.

If we talk more about MERN Stack, it comprises-MongoDB, Express.js, React.js, and Node.js.

Let’s have an overview of these four.

MongoDB

A non-relational database. As it is a document database, it stores data in JSON-like documents and these documents also support arrays and nested objects. Example:-

{ “id”: objectid=(“7basd3366g789fffff”),  “title”: “About MONGODB”,  “content”: “MongoDB is a non relational database”,  “comments: [
{“name” : “abc”, “email”: “abc@gmail.com”},
{“name” : “xyz”, “email”: “xyz@gmail.com”}
]
}

Now the question is that why we require MongoDB when we already have awesome databases like MySQL, PostgreSQL, etc. Let’s answer it.

If data cannot be represented in the form of a table or maybe different instances of an object have different fields then a fixed table kind of structure cannot help out. Many times this leads to the creation of many tables, across which each entity is spread. This can make accessing the data slowly. It is more desirable to keep all the data that are accessed together should be stored together. Here MongoDB can be helpful.

Features of MongoDB

  • Has Document-Oriented storage.
  • Has a single master with built-in replication support.
  • Ships with built-in sharding support ( spreading data around several replicated clusters).
  • It has very wide driver support, although databases ship with limited support, MongoDB has drivers for every language.
  • Provide horizontal scalability to balance the increasing load of modern applications.
  • Robust, flexible, and scale-able.

Let’s make the MongoDB sample Database

const mongoose = require('mongoose');
const validator = require('validator');// Defining User collection schema structure.
// We have name, email, password field.const userSchema = mongoose.Schema({
name: {
type: String,
require: true,
trim: true
},
email: {
type: String,
required: true,
trim: true,
lowercase: true,
unique: true,
validate(value){
if(!validator.isEmail(value)){
throw new Error('Email is invalid')
}
}
},
password: {
type: String,
required: true,
trim: true,
minlength: 7,
validate(value){
if(value.toLowerCase().includes('password')){
throw new Error('Password cannot contain "Password"')
}
}
}

})const User = mongoose.model('User', userSchema)
module.exports = User

Express.js

A server-side framework that helps to develop the web and mobile application (Single-page, multi-page, and hybrid mobile and web apps). It runs on the Node.js platform. Express Generator facilitates the creation of complex applications quickly.

Features of Express.js

  • Makes Node.js web application development fast and easy.
  • Easy to configure and customize.
  • It allows you to define routes of your application based on HTTP methods and URLs.
  • Has two templating engines, Jade and EJS, which facilitate the flow of data into a website structure
  • Includes various middleware modules that you can use to perform additional tasks on request and response.
  • It allows you to define an error handling middleware.
  • It allows you to create a REST API server.
  • Easy to connect with databases such as MongoDB.

Read Express documentation here http://expressjs.com/

React.js

The most popular front-end JavaScript library. It facilitates fast and interactive user interfaces for web and mobile applications. It’s an open-source library with a component-based approach. In a Model View Controller architecture, React is the View layer, which is responsible for how the app looks and feels. Refer to this Github Repository to check a simple project based on React.js. Now React.js is more popular than all other front-end development frameworks. Reasons are:

1. Easy to learn, as it mostly combines basic HTML and JavaScript concepts with some additional concepts. But, yes some time is required to get knowledge of the Javascript library.

2. The basic building block of React application is COMPONENTS and these components can be created once and used in multiple applications. In the below image we have a searchBox component that can be imported in any project.

import React from 'react'; 
const SearchBox = ({ searchfield, searchChange }) => {
return (
<div className='pa2'>
<input
className='pa3 ba b--green bg-lightest-blue'
type='search'
placeholder='search robots'
onChange={searchChange}
/>
</div>
);
}
export default SearchBox;

3. It creates web applications faster, as it uses virtual DOM which compares the components’ previous states and updates only the items in the Real DOM that were changed, instead of updating all of the components again.

4. It can be used for both web and mobile app development. React Native is a framework, derived from React.js only, used to create web applications.

5. React is a library, so, it gives you the tools to build your application. With a library, a developer can design his or her application with complete freedom to pick and choose from the library’s functions.

6. As React can run on the server, its code can be used on both browsers and servers. It means you can create pages on the server whenever you want to.

How to start with React

To start with React, firstly we need to set up the React environment on our device. Firstly make sure you have NPM and Node.js installed on your device. If not download from here.

On your terminal run below command

npx create-react-app helloreact
cd helloreact
npm start

The create-react-app will set up everything you need to run a React application. A new browser window will pop up as we run npm start command. If not, open your browser and type localhost:3000 in the address bar. Results are:

Now in your text editor, open location /myfirstreact/src/App.js. Clear App.js and paste the code below:

import React, { Component } from 'react';

class App extends Component {
render() {
return (
<div className="App">
<h1>Hello World!</h1>
</div>
);
}
}

export default App;

Results will be

This is how our helloreact app will look like when we render h1 element.

Node.js

A server-side programming framework. It is built on Chrome’s JavaScript engine, which provides event-driven and non-blocking I/O.

Why Node.js

Since Node.js uses asynchronous programming and this is the main reason for using it above PHP and ASP.net.

See how Node.js handles a file request:

  1. Sends the task to the computer’s file system.
  2. Ready to handle the next request(while PHP and ASP wait for the file system to open and read the file.
  3. When the file system has opened and read the file, the server returns the content to the client.

So it eliminates the waiting and continues with the next request to be made.

To know more about the Node.js refer to this blog.

Lets Do Hello World! with NodeJs

First, we have to run the following commands in the terminal.

$ npm i express

Then import the module in the project.

const express = require('express');
const app = express();const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
req.send('Hello World');
}
app.listen(port, () => {
console.log('Server is up to ' + port)
}

Result will be

Other Features with MERN

Efficiency:-Highly efficient code with less time can be developed with MERN Stack.

Testing:-It is crucial and the first string for the software development process. There are lots of work already done for testing React.js applications, you can use many common tools such as Jest, Mocha, etc

Implementation:- There is a common HTML-like, hybrid code formatting in React.js called as JSX. It allows you to implement your idea more quickly. The HTML like content in the below code looks like HTML but it is JSX.

import React from ‘react’; 
const Card = ({ name, email, id }) => {
return (
<div className=’tc grow bg-red br3 pa3 ma2 dib bw2 shadow-5'>
<img alt=’robots’ src={`https://robohash.org/}/>
<div>
<h2>{name}</h2>
<p>{email}</p>
</div>
</div>
);
}
export default Card;

Javascript-based:-Since every line of code is written in JavaScript( both for client-side code and server-side code), so there is no requirement of context switching.

MEAN VS MERN

Here is the answer to the second question in the heading. MEAN has been in the market for a longer time but MERN is gaining popularity now. MEAN stack comprises four open-source technologies -MongoDB, Express.js, Angular.js, and Node.js. Seen from abbreviations when it comes to comparing these two stacks, it is all about Angular Vs React. And as we have discussed React is a library but Angular is a complete framework and so it will not be worthy to compare the two. When it comes to build large applications, obviously MEAN will help you out, but the MERN stack is ideal when you want faster development in small applications.

Advantages of MERN Stack!

  1. UI rendering and performance

React JS is the best when it is about UI layer abstraction. Since React is only a library, it provides you the freedom to build the application and organize the code however you want. So, it is better than Angular in terms of UI rendering and performance.

2. Cost-Effective

As MERN Stack uses one language throughout that is Javascript so it will be beneficial for a company to hire Javascript experts only rather than hiring different specialists for different technology. This move will save a lot of time and money.

3. Open Source

All technologies that are involved in MERN are open-source. This feature allows a developer to get solutions to queries that may evolve during development, from the available open portals. As a result, it will be beneficial for a developer.

4. Easy to switch between client and server

As everything is written in one language this is why MERN is simple and fast. And also it is easy to switch between client and server.

Disadvantages of MERN Stack!

1. Productivity

Since React is just a library it uses many third-party libraries which provides lower developer productivity. And due to this upgrading, the React code requires more effort.

2. Large-Scale Applications

It becomes difficult with MERN to make a large project in which many developers are involved. MERN stack is best suited for single-page applications.

3. Error prevention:
If you want a technology stack that prevents common coding errors by its very design, then the MEAN stack is a better choice. As Angular uses Typescript, so prevents common coding errors at the coding stage itself. However, React lags behind here.

Summary

So now we know about all the technologies that are involved in MERN STACK. We have also learned how giant React.js is in today’s tech world. And our MERN VS MEAN concludes that the selection of stack completely depends upon the functional requirement of the system to be developed. If you want to have deeper dive in MERN Stack you can go through these course on UDEMY- Great MERN STACK COURSE ON UDEMY -MERN Stack Front To Back: Full Stack React, Redux & Node.js

So if you are going to choose the MERN stack for your next project, definitely you are going to have an awesome experience.

Feel free to connect with us read more articles from Aeologic.com.

Aeologic Technologies is a dynamic, solution, and value-driven technology company. We position ourselves as a new generation cutting edge technology company. We work creatively to enable businesses with leading technologies and solutions. You can connect with us on Facebook, Twitter, and LinkedIn for any queries.

--

--

Divyani Tyagi
Aeologic

Software Engineer Intern at Aeologic Technologies