Mern Stack Basics

What is the MERN Stack?

The MERN stack is a web development framework consisting of the following open-source components:

  1. MongoDB:
  • A document-oriented NoSQL database.
  • Known for scalability, rich queries, and auto-sharding.
  1. Express.js:
  • A Node.js web application framework.
  • Handles HTTP logic efficiently.
  1. React.js:
  • A popular JavaScript library.
  • Executed in the browser or on the backend server within Node.js.
  1. Node.js:
  • An execution environment for event-driven, server-side, and networking operations.

How to Get Started with the MERN Stack

MERN is like a toolbox for creating whole websites. We’re going to use it to build a project with two main parts: the front end (client) and the back end (server). The client, made with React, is what users see, and the server, built with MongoDB, Node, and Express, handles behind-the-scenes work. This project will help us learn how to use MERN effectively.

Step 1: Install Node

To install Node, type  https://nodejs.org/en/ and download either the LTS version or the current version.

Step 2: Create a New Node Project

Now that you have Node.js and MongoDB installed, let’s set up a project directory for your Node project. Open a new terminal window and create a new Node project directory anywhere you prefer on your computer. Switch to that directory by using the following code:

> mkdir myProject && cd myProject 

> mkdir server && cd server

Thus, we can initialize a new Node,js project with the code given below:

> npm init -y

Creating the package.json file helps organize information about your app and the dependencies it requires to run. This file serves as a kind of blueprint for your project.

Then, we have to download the dependencies:

> npm install express cors dotenv

The command provided above will use various keyword

Express simplifies web development for Node.js, making it more convenient.
Cors is a Node.js package facilitating cross-origin resource sharing.
Dotenv loads environment variables from a .env file into process.env, separating configuration from code.
You can verify the installed dependencies in the package.json file, which should list them along with their versions.

Step 3: Create a Node.js Express Server

We can start by making a file in the name called server.js and then enter the following code

const express = require("express");

const app = express();

const cors = require("cors");

require("dotenv").config({ path: "./config.env" });
const port = process.env.PORT || 5000;

app.use(cors());

app.use(express.json());

app.use(require("./routes/record"));

// Get MongoDB driver connection
const dbo = require("./db/conn");
 
app.listen(port, () => {
  // Perform a database connection when server starts
  dbo.connectToServer(function (err) {
    if (err) console.error(err);
 
  });
  console.log(`Server is running on port: ${port}`);
});

Step 4: Install Mongoose and MongoDB

In this guide, we’ll use the MongoDB Atlas cloud-based database-as-a-service free tier, making it easy to start with MongoDB. Mongoose will serve as the interface to your MongoDB database. Mongoose is a tool for MongoDB object modeling, designed to function in an asynchronous environment.

To add Mongoose to your Node.js project (package.json), you can install it like any other dependency using npm. Execute the following command within your project folder:

> npm install mongoose

This command can add Mongoose and MongoDB database driver that could further enable Node.js applications to connect to the database and work with the data.

Step 5: Connect to MongoDB Database

Now, we can connect their server to the database. Later, open the terminal window inside the server directory and perform the following command

> touch config.env

Here are the steps to configure your MongoDB Atlas database connection:

  1. Open the config.env file and create a new variable named ATLAS_URI to store the connection string.
  2. In your MongoDB Atlas account, navigate to your cluster and click on CONNECT. This action will launch the Cluster Connection Wizard.
  3. Follow the prompts in the Wizard, which may include adding your current IP address to the IP Access List and creating a new MongoDB user. Make a note of the username and password for the MongoDB user.
  4. In the Wizard, choose “Connect Your Application” when prompted to select a connection method. For the driver version, select Node.js and 3.6 or later.
  5. Copy the provided connection string from the Wizard.

You’ll use this connection string (from step 5) to set the value of ATLAS_URI in your config.env file.

Then, make a new folder in the name of ‘db’ under the server directory.

> mkdir db && cd db

Moreover, inside it,we have to make a file such as cobb.js. So, we can add the following code to connect to our database.

> touch conn.js
const { MongoClient } = require("mongodb");
const Db = process.env.ATLAS_URI;
const client = new MongoClient(Db, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
 
var _db;
 
module.exports = {
  connectToServer: function (callback) {
    client.connect(function (err, db) {
      // Verify we got a good "db" object
      if (db)
      {
        _db = db.db("employees");
        console.log("Successfully connected to MongoDB."); 
      }
      return callback(err);
         });
getDb: function () {
    return _db;
  },
};

Step 6: Create the Server API Endpoints/ Routes

  1. Navigate to your “server” directory.
  2. Inside the “server” directory, create a new folder named “routes.”
  3. Inside the “routes” folder, create a new file named “record.js.”

These steps will help you organize your project structure and create a dedicated file for handling API endpoints.

> cd ../server && mkdir routes

> touch routes/record.js

Then, we can paste the code inside the routes/record.js folder:

const express = require("express");
 
// recordRoutes is an instance of the express router.
// We use it to define our routes.
// The router will be added as a middleware and will take control of requests starting with path /record.
const recordRoutes = express.Router();
 
// This will help us connect to the database
const dbo = require("../db/conn");
 
// This helps convert the id from string to ObjectId for the _id.
const ObjectId = require("mongodb").ObjectId;
 
 
// This section will help you get a list of all the records.
recordRoutes.route("/record").get(function (req, res) {
 let db_connect = dbo.getDb("employees");
 db_connect
   .collection("records")
   .find({})
.toArray(function (err, result) {
     if (err) throw err;
     res.json(result);
   });
});
 
// This section will help you get a single record by id
recordRoutes.route("/record/:id").get(function (req, res) {
 let db_connect = dbo.getDb();
 let myquery = { _id: ObjectId(req.params.id) };
 db_connect
.collection("records")
   .findOne(myquery, function (err, result) {
     if (err) throw err;
     res.json(result);
   });
});
// This section will help you create a new record.
recordRoutes.route("/record/add").post(function (req, response) {
 let db_connect = dbo.getDb();
 let myobj = {
   name: req.body.name,
   position: req.body.position,
   level: req.body.level,
 };
 db_connect.collection("records").insertOne(myobj, function (err, res) {
   if (err) throw err;
   response.json(res);
 });
});
 // This section will help you update a record by id.
recordRoutes.route("/update/:id").post(function (req, response) {
 let db_connect = dbo.getDb();
 let myquery = { _id: ObjectId(req.params.id) };
 let newvalues = {
   $set: {
     name: req.body.name,
     position: req.body.position,
     level: req.body.level,
   },
 };
 db_connect
   .collection("records")
   .updateOne(myquery, newvalues, function (err, res) {
     if (err) throw err;
     console.log("1 document updated");
     response.json(res);
   });
});
// This section will help you delete a record
recordRoutes.route("/:id").delete((req, response) => {
 let db_connect = dbo.getDb();
 let myquery = { _id: ObjectId(req.params.id) };
 db_connect.collection("records").deleteOne(myquery, function (err, obj) {
   if (err) throw err;
   console.log("1 document deleted");
   response.json(obj);
 });
});
 
module.exports = recordRoutes;

Now, we can begin your server and check if it works. Then, open your terminal in the same directory as the server.js file and type:

> node server.js

If everything is done correctly, the following output will be received.

Server is running on port: 5000
Successfully connected to MongoDB.

Step 7: Create a React Application

Download the react application and perform the create -react- app command in the project root folder:

> npx create-react-app client

The new directory for the React frontend app will be made. Then, explore the client folder and monitor the react application code

> cd client && ls

Now, we can open the new terminal window which is available in the client directory and download the two additional dependencies

> npm install bootstrap 
react-router-dom

Step 8: Set Up the React Router

To set up the React Router, we have to begin by emptying the src folder:

> rm src/**/*

Add two new files in  index.js and App.js.

> touch src/index.js src/App.js

Then, add the code inside the src/index.js file

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { BrowserRouter } from "react-router-dom";

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById("root")
);

Step 9: Create the React Components

Create a components folder inside the src directory. For each component we create, we will add a new .js file inside the components folder.

There are three things that the app needs to do:

– We can Create an employee

– It can also Edit employees

– It can View all employees

For each task, we will create create.jsedit.jsnavbar.js, and recordList.js

> mkdir src/components
(cd src/components &&
touch create.js edit.js navbar.js recordList.js)

Step 10: Testing

Now, we have completed creating the components. We have connected your React app to the back end using fetch. fetch provides cleaner and easier ways to handle http requests. fetch is used in create.js, edit.js, and recordList.js as they handle http requests.

Close everything and start the app, using the following steps:

In a new terminal window, start by executing the following command in the ‘server‘ directory:

> node server.js

Then, open the new terminal window in the client directory and run the following command

> npm start

FAQ on Mern Stack Basics

Q1. Is MERN stack for beginners?

Ans. The MERN stack is a very well-known tech stack used to build web applications.

Q2. What is the MERN stack?

Ans. MERN stands for MongoDB, Express, React, Node, these are the four key technologies that make up the stack. MongoDB — document database. Express(.js) — Node.js web framework. React(.js) — a client-side JavaScript framework.

Q3. Which language is used in MERN?

Ans. Javascript

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

Leave a Comment