{"id":4156,"date":"2024-03-06T11:54:58","date_gmt":"2024-03-06T11:54:58","guid":{"rendered":"https:\/\/www.skillvertex.com\/blog\/?p=4156"},"modified":"2024-03-06T11:54:58","modified_gmt":"2024-03-06T11:54:58","slug":"mern-stack-basics","status":"publish","type":"post","link":"https:\/\/www.skillvertex.com\/blog\/mern-stack-basics\/","title":{"rendered":"Mern Stack Basics"},"content":{"rendered":"\n<div class=\"wp-block-rank-math-toc-block\" id=\"rank-math-toc\" id=\"rank-math-toc\"><p>Table of Contents<\/p><nav><ul><li ><a href=\"#what-is-the-mern-stack\">What is the MERN Stack?<\/a><\/li><li ><a href=\"#how-to-get-started-with-the-mern-stack\">How to Get Started with the MERN Stack<\/a><ul><li ><a href=\"#step-1-install-node\">Step 1: Install Node<\/a><\/li><li ><a href=\"#step-2-create-a-new-node-project\">Step 2: Create a New Node Project<\/a><\/li><li ><a href=\"#step-3-create-a-node-js-express-server\">Step 3: Create a Node.js Express Server<\/a><\/li><li ><a href=\"#step-4-install-mongoose-and-mongo-db\">Step 4: Install Mongoose and MongoDB<\/a><\/li><li ><a href=\"#step-5-connect-to-mongo-db-database\">Step 5: Connect to MongoDB Database <\/a><\/li><li ><a href=\"#step-6-create-the-server-api-endpoints-routes\">Step 6: Create the Server API Endpoints\/ Routes<\/a><\/li><li ><a href=\"#step-7-create-a-react-application\">Step 7: Create a React Application<\/a><\/li><li ><a href=\"#step-8-set-up-the-react-router\">Step 8: Set Up the React Router<\/a><\/li><li ><a href=\"#step-9-create-the-react-components\">Step 9: Create the React Components <\/a><\/li><li ><a href=\"#step-10-testing\">Step 10: Testing<\/a><\/li><\/ul><\/li><li ><a href=\"#faq-on-mern-stack-basics\">FAQ on Mern Stack Basics<\/a><\/li><\/ul><\/nav><\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"what-is-the-mern-stack\">What is the MERN Stack?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The MERN stack is a web development framework consisting of the following open-source components:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>MongoDB:<\/strong><\/li>\n<\/ol>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A document-oriented NoSQL database.<\/li>\n\n\n\n<li>Known for scalability, rich queries, and auto-sharding.<\/li>\n<\/ul>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Express.js:<\/strong><\/li>\n<\/ol>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A Node.js web application framework.<\/li>\n\n\n\n<li>Handles HTTP logic efficiently.<\/li>\n<\/ul>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>React.js:<\/strong><\/li>\n<\/ol>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A popular JavaScript library.<\/li>\n\n\n\n<li>Executed in the browser or on the backend server within Node.js.<\/li>\n<\/ul>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Node.js:<\/strong><\/li>\n<\/ol>\n\n\n\n<ul class=\"wp-block-list\">\n<li>An execution environment for event-driven, server-side, and networking operations.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"how-to-get-started-with-the-mern-stack\">How to Get Started with the MERN Stack<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">MERN is like a toolbox for creating whole websites. We&#8217;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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"step-1-install-node\">Step 1: Install Node<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">To install Node,  type &nbsp;<strong>https:\/\/nodejs.org\/en\/<\/strong>&nbsp;and download either the LTS version or the current version.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"step-2-create-a-new-node-project\">Step 2: Create a New Node Project<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Now that you have Node.js and MongoDB installed, let&#8217;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:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&gt; mkdir myProject &amp;&amp; cd myProject \n\n&gt; mkdir server &amp;&amp; cd server<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Thus, we can initialize a new Node,js project with the code given below:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&gt; npm init -y<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Then, we have to download the dependencies:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&gt; npm install express cors dotenv\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The command provided above will use various keyword<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Express simplifies web development for Node.js, making it more convenient.<br>Cors is a Node.js package facilitating cross-origin resource sharing.<br>Dotenv loads environment variables from a .env file into process.env, separating configuration from code.<br>You can verify the installed dependencies in the package.json file, which should list them along with their versions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"step-3-create-a-node-js-express-server\">Step 3: Create a Node.js Express Server<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">We can start by making a file in the name called server.js  and then enter the following code<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const express = require(\"express\");\n\nconst app = express();\n\nconst cors = require(\"cors\");\n\nrequire(\"dotenv\").config({ path: \".\/config.env\" });\nconst port = process.env.PORT || 5000;\n\napp.use(cors());\n\napp.use(express.json());\n\napp.use(require(\".\/routes\/record\"));\n\n\/\/ Get MongoDB driver connection\nconst dbo = require(\".\/db\/conn\");\n \napp.listen(port, () =&gt; {\n  \/\/ Perform a database connection when server starts\n  dbo.connectToServer(function (err) {\n    if (err) console.error(err);\n \n  });\n  console.log(`Server is running on port: ${port}`);\n});<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"step-4-install-mongoose-and-mongo-db\">Step 4: Install Mongoose and MongoDB<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">In this guide, we&#8217;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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&gt; npm install mongoose\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"step-5-connect-to-mongo-db-database\"><strong>Step 5: Connect to MongoDB Database<\/strong><br><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Now, we can connect their server to the database. Later, open the terminal window inside the server directory and perform the following command<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&gt; touch config.env\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here are the steps to configure your MongoDB Atlas database connection:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Open the config.env file and create a new variable named ATLAS_URI to store the connection string.<\/li>\n\n\n\n<li>In your MongoDB Atlas account, navigate to your cluster and click on CONNECT. This action will launch the Cluster Connection Wizard.<\/li>\n\n\n\n<li>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.<\/li>\n\n\n\n<li>In the Wizard, choose &#8220;Connect Your Application&#8221; when prompted to select a connection method. For the driver version, select Node.js and 3.6 or later.<\/li>\n\n\n\n<li>Copy the provided connection string from the Wizard.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">You&#8217;ll use this connection string (from step 5) to set the value of ATLAS_URI in your config.env file.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Then, make a new folder in the name of &#8216;db&#8217; under the server directory.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&gt; mkdir db &amp;&amp; cd db\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&gt; touch conn.js\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>const { MongoClient } = require(\"mongodb\");\nconst Db = process.env.ATLAS_URI;\nconst client = new MongoClient(Db, {\n  useNewUrlParser: true,\n  useUnifiedTopology: true,\n});\n \nvar _db;\n \nmodule.exports = {\n  connectToServer: function (callback) {\n    client.connect(function (err, db) {\n      \/\/ Verify we got a good \"db\" object\n      if (db)\n      {\n        _db = db.db(\"employees\");\n        console.log(\"Successfully connected to MongoDB.\"); \n      }\n      return callback(err);\n         });\ngetDb: function () {\n    return _db;\n  },\n};<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"step-6-create-the-server-api-endpoints-routes\">Step 6: Create the Server API Endpoints\/ Routes<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Navigate to your &#8220;server&#8221; directory.<\/li>\n\n\n\n<li>Inside the &#8220;server&#8221; directory, create a new folder named &#8220;routes.&#8221;<\/li>\n\n\n\n<li>Inside the &#8220;routes&#8221; folder, create a new file named &#8220;record.js.&#8221;<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">These steps will help you organize your project structure and create a dedicated file for handling API endpoints.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&gt; cd ..\/server &amp;&amp; mkdir routes\n\n&gt; touch routes\/record.js<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Then, we can paste the code inside the routes\/record.js folder:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const express = require(\"express\");\n \n\/\/ recordRoutes is an instance of the express router.\n\/\/ We use it to define our routes.\n\/\/ The router will be added as a middleware and will take control of requests starting with path \/record.\nconst recordRoutes = express.Router();\n \n\/\/ This will help us connect to the database\nconst dbo = require(\"..\/db\/conn\");\n \n\/\/ This helps convert the id from string to ObjectId for the _id.\nconst ObjectId = require(\"mongodb\").ObjectId;\n \n \n\/\/ This section will help you get a list of all the records.\nrecordRoutes.route(\"\/record\").get(function (req, res) {\n let db_connect = dbo.getDb(\"employees\");\n db_connect\n   .collection(\"records\")\n   .find({})\n.toArray(function (err, result) {\n     if (err) throw err;\n     res.json(result);\n   });\n});\n \n\/\/ This section will help you get a single record by id\nrecordRoutes.route(\"\/record\/:id\").get(function (req, res) {\n let db_connect = dbo.getDb();\n let myquery = { _id: ObjectId(req.params.id) };\n db_connect\n.collection(\"records\")\n   .findOne(myquery, function (err, result) {\n     if (err) throw err;\n     res.json(result);\n   });\n});\n\/\/ This section will help you create a new record.\nrecordRoutes.route(\"\/record\/add\").post(function (req, response) {\n let db_connect = dbo.getDb();\n let myobj = {\n   name: req.body.name,\n   position: req.body.position,\n   level: req.body.level,\n };\n db_connect.collection(\"records\").insertOne(myobj, function (err, res) {\n   if (err) throw err;\n   response.json(res);\n });\n});\n \/\/ This section will help you update a record by id.\nrecordRoutes.route(\"\/update\/:id\").post(function (req, response) {\n let db_connect = dbo.getDb();\n let myquery = { _id: ObjectId(req.params.id) };\n let newvalues = {\n   $set: {\n     name: req.body.name,\n     position: req.body.position,\n     level: req.body.level,\n   },\n };\n db_connect\n   .collection(\"records\")\n   .updateOne(myquery, newvalues, function (err, res) {\n     if (err) throw err;\n     console.log(\"1 document updated\");\n     response.json(res);\n   });\n});\n\/\/ This section will help you delete a record\nrecordRoutes.route(\"\/:id\").delete((req, response) =&gt; {\n let db_connect = dbo.getDb();\n let myquery = { _id: ObjectId(req.params.id) };\n db_connect.collection(\"records\").deleteOne(myquery, function (err, obj) {\n   if (err) throw err;\n   console.log(\"1 document deleted\");\n   response.json(obj);\n });\n});\n \nmodule.exports = recordRoutes;<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&gt; node server.js\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If everything is done correctly,  the following output will be received.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Server is running on port: 5000\nSuccessfully connected to MongoDB.<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"step-7-create-a-react-application\">Step 7: Create a React Application<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Download the react application and perform the create -react- app command in the project root folder:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&gt; npx create-react-app client\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The new directory for the React frontend app will be made. Then, explore the client folder and monitor the react application code<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&gt; cd client &amp;&amp; ls\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Now, we can open the new terminal window which is available in the client directory and download the two additional dependencies<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&gt; npm install bootstrap \nreact-router-dom<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"step-8-set-up-the-react-router\">Step 8: Set Up the React Router<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">To set up the React Router, we have to begin by emptying the&nbsp;<strong>src<\/strong>&nbsp;folder:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&gt; rm src\/**\/*\n<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"add-two-new-files-in-index-js-and-app-js\">Add two new files in &nbsp;<strong>index.js&nbsp;<\/strong>and&nbsp;<strong>App.js<\/strong>.<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>&gt; touch src\/index.js src\/App.js\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Then, add the  code inside the src\/index.js file<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import React from \"react\";\nimport ReactDOM from \"react-dom\";\nimport App from \".\/App\";\nimport { BrowserRouter } from \"react-router-dom\";\n\nReactDOM.render(\n  &lt;React.StrictMode&gt;\n    &lt;BrowserRouter&gt;\n      &lt;App \/&gt;\n    &lt;\/BrowserRouter&gt;\n  &lt;\/React.StrictMode&gt;,\n  document.getElementById(\"root\")\n);<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"step-9-create-the-react-components\">Step 9: Create the React Components<br><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create a&nbsp;<strong><em>components<\/em><\/strong>&nbsp;folder inside the&nbsp;<em>src<\/em>&nbsp;directory. For each component we create, we will add a new .js file inside the&nbsp;<em>components<\/em>&nbsp;folder.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There are three things that the app needs to do:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">\u2013 We can Create an employee<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">\u2013 It can also Edit employees<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">\u2013 It can View all employees<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For each task, we will create&nbsp;<strong>create.js<\/strong>,&nbsp;<strong>edit.js<\/strong>,&nbsp;<strong>navbar.js<\/strong>, and recordList.js<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&gt; mkdir src\/components\n(cd src\/components &amp;&amp;\ntouch create.js edit.js navbar.js recordList.js)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"step-10-testing\">Step 10: Testing<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Close everything and start the app, using the following steps:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In a new terminal window, start by executing the following command in the \u2018<strong>server<\/strong>\u2018 directory:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&gt; node server.js\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Then, open the new terminal window in the client directory and run the following command<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&gt; npm start\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"faq-on-mern-stack-basics\">FAQ on Mern Stack Basics<\/h2>\n\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1701780680305\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q1. Is MERN stack for beginners?<\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans. The MERN stack is a very well-known tech stack used to build web applications.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1701780689268\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q2. What is the MERN stack?<\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans. MERN stands for\u00a0MongoDB, Express, React, Node, these are the four key technologies that make up the stack. MongoDB \u2014 document database. Express(.js) \u2014 Node.js web framework. React(.js) \u2014 a client-side JavaScript framework.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1701780784835\" class=\"rank-math-list-item\">\n<h4 class=\"rank-math-question \">Q3. Which language is used in MERN?<\/h4>\n<div class=\"rank-math-answer \">\n\n<p>Ans. Javascript <\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>What is the MERN Stack? The MERN stack is a web development framework consisting of the following open-source components: How to Get Started with the MERN Stack MERN is like a toolbox for creating whole websites. We&#8217;re going to use it to build a project with two main parts: the front end (client) and the &#8230; <a title=\"Mern Stack Basics\" class=\"read-more\" href=\"https:\/\/www.skillvertex.com\/blog\/mern-stack-basics\/\" aria-label=\"More on Mern Stack Basics\">Read more<\/a><\/p>\n","protected":false},"author":4,"featured_media":5500,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[736],"tags":[755],"class_list":["post-4156","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-mern-stack","tag-mern-stack-basics","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-33"],"_links":{"self":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/4156","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/comments?post=4156"}],"version-history":[{"count":9,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/4156\/revisions"}],"predecessor-version":[{"id":7972,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/posts\/4156\/revisions\/7972"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/media\/5500"}],"wp:attachment":[{"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/media?parent=4156"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/categories?post=4156"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.skillvertex.com\/blog\/wp-json\/wp\/v2\/tags?post=4156"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}