0% found this document useful (0 votes)
105 views17 pages

Let'S Build A Full Stack Mongodb, React, Node and Express (Mern) App

The document is a tutorial for building a full-stack web application using MongoDB, React, Node, and Express (MERN). It guides the reader through setting up the backend with Node/Express and MongoDB for the database. It then sets up the frontend with React using create-react-app. The tutorial has the reader build basic CRUD functionality to view, add, update and delete data from the MongoDB database using the React frontend and Node/Express backend APIs.

Uploaded by

MAster Chief117
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
105 views17 pages

Let'S Build A Full Stack Mongodb, React, Node and Express (Mern) App

The document is a tutorial for building a full-stack web application using MongoDB, React, Node, and Express (MERN). It guides the reader through setting up the backend with Node/Express and MongoDB for the database. It then sets up the frontend with React using create-react-app. The tutorial has the reader build basic CRUD functionality to view, add, update and delete data from the MongoDB database using the React frontend and Node/Express backend APIs.

Uploaded by

MAster Chief117
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Let’s build a full stack MongoDB, React, Node an... https://medium.com/javascript-in-plain-english/full...

Let’s build a full stack MongoDB,


React, Node and Express (MERN)
app
jelo rivera Follow
Sep 12, 2018 · 6 min read

“Pillars uphold the temple”

1 of 17 7/30/19, 2:49 AM
Let’s build a full stack MongoDB, React, Node an... https://medium.com/javascript-in-plain-english/full...

When I wanted to upgrade from being a Front End Developer to a Full


Stack Developer, I had trouble finding an article that encompassed
the concepts of all the different skills I needed to learn in able to
become one.

Knowledge of databases, familiarity with a back-end language and


how to integrate the back-end with my front-end app were skills that I
didn’t know yet. That is what pushed me to create this article: to solve
that in order to help myself and for my fellow software engineers out
there.

I’ve included the git repository link of the whole code at the end of the
article but I suggest that you take this article step-by-step before
checking the repo out. It will help you understand the tutorial better.
:)

“What will we build”

2 of 17 7/30/19, 2:49 AM
Let’s build a full stack MongoDB, React, Node an... https://medium.com/javascript-in-plain-english/full...

Here is what our app will look like once we’ve finished building it.

The front end allows us to view the current information inside our
database. It also allows us to add new data into it, delete a present
data and update an already existing one.

We will build it from nothing. We will setup our own database, create
the back end from the ground up and bootstrap our front end with the
bare minimum.

So, get yourselves strapped in and get your coding fingers ready!

First Things First


Let’s create our project’s main directory. This will hold both the code
for the front and back end of our app.

mkdir fullstack_app && cd fullstack_app

Then, let’s start off with our front end. We will use create-react-app to
bootstrap our front end, which means that we will not have to worry
about setting up Webpack or Babel (as create-react-app sorts this all
out by default). If you don’t have create-react-app globally installed
yet, fret not, installing it is easy, just type this into our project’s main
directory command line.

3 of 17 7/30/19, 2:49 AM
Let’s build a full stack MongoDB, React, Node an... https://medium.com/javascript-in-plain-english/full...

npm i -g create-react-app

After this, we can now create our react app with create-react-app (pun
intended). To do this, just type this in the command line.

create-react-app client && cd client

We will also need Axios in order to make get/post requests with ajax.
So let’s install that now:

npm i -S axios

Wait for it to finish and then let’s proceed in organizing the front end
so it will be easy to incorporate our back end later.

For PC users:

del src\App.css src\App.test.js src\index.css src\logo.svg\

For MAC users:

4 of 17 7/30/19, 2:49 AM
Let’s build a full stack MongoDB, React, Node an... https://medium.com/javascript-in-plain-english/full...

rm src/App.css src/App.test.js src/index.css src/logo.svg

Then, let’s edit our App.js file inside the client folder and let it just
render something simple. We will further edit this file later on when
we have our back end ready.

1 // client/src/App.js
2 import React, { Component } from "react";
3
4 class App extends Component {
5 render() {
6 return <div>I'M READY TO USE THE BACK END APIS! :-)</div>;
7 }
8 }
9
10 export default App;

App.jsx hosted with ❤ by GitHub view raw


“React app ready”

We also have to edit our index.js and remove one line of code from
there. We just have to remove the import ‘./index.css’; part of the code
and we can now start our react app.

5 of 17 7/30/19, 2:49 AM
Let’s build a full stack MongoDB, React, Node an... https://medium.com/javascript-in-plain-english/full...

1 // client/src/index.js
2
3 import React from 'react';
4 import ReactDOM from 'react-dom';
5 import App from './App';
6 import registerServiceWorker from './registerServiceWorker';
7
8 ReactDOM.render(<App />, document.getElementById('root'));
9 registerServiceWorker();

index.jsx hosted with ❤ by GitHub view raw


“index.js”

In order to start our front end, just type this in the command line.

npm start

and go to your browser and type http://localhost:3000/. You can now


see that our front end is up and running.

Back It Up Just a Tad


Time to set-up our back end. Go back to our main directory and let’s
create our back end directory from there. We will also initialize this
directory so that we’ll have our package.json ready for building. Your
terminal will prompt you to enter some details for the package.json,
just keep pressing enter until it is done.

mkdir backend && cd backend


npm init

6 of 17 7/30/19, 2:49 AM
Let’s build a full stack MongoDB, React, Node an... https://medium.com/javascript-in-plain-english/full...

Create a new file that will serve as our main code for the back end and
name it server.js. Then, type the following into it. This back end code
is pretty blunt and basic, I have only created it so that beginners won’t
have to think much of the complexity of the code rather than they
would think about the code’s intent. Then, they could easy
manipulate it afterwards once they wrapped their heads around it.
I’ve put comments beside every method for ease of understanding.

7 of 17 7/30/19, 2:49 AM
Let’s build a full stack MongoDB, React, Node an... https://medium.com/javascript-in-plain-english/full...

1 const mongoose = require('mongoose');


2 const express = require('express');
3 var cors = require('cors');
4 const bodyParser = require('body-parser');
5 const logger = require('morgan');
6 const Data = require('./data');
7
8 const API_PORT = 3001;
9 const app = express();
10 app.use(cors());
11 const router = express.Router();
12
13 // this is our MongoDB database
14 const dbRoute =
15 'mongodb://<your-db-username-here>:<your-db-password-here>@ds249583.mlab.com:49583/fullstack_
16
17 // connects our back end code with the database
18 mongoose.connect(dbRoute, { useNewUrlParser: true });
19
20 let db = mongoose.connection;
21
22 db.once('open', () => console.log('connected to the database'));
23
24 // checks if connection with the database is successful
25 db.on('error', console.error.bind(console, 'MongoDB connection error:'));
26
27 // (optional) only made for logging and
28 // bodyParser, parses the request body to be a readable json format
29 app.use(bodyParser.urlencoded({ extended: false }));
30 app.use(bodyParser.json());
31 app.use(logger('dev'));
32
33 // this is our get method
34 // this method fetches all available data in our database
35 router.get('/getData', (req, res) => {
36 Data.find((err, data) => {
37 if (err) return res.json({ success: false, error: err });
38 return res.json({ success: true, data: data });
39 });
40 });

8 of 17 7/30/19, 2:49 AM
Let’s build a full stack MongoDB, React, Node an... https://medium.com/javascript-in-plain-english/full...

“Spine of every web app”

You might have noticed that a database link is already used in our
back end code. Don’t worry, that’s the next step in our article. Setting
it up will also be as easy as the past few steps. First, head on to
MongoDB atlas and create an account there. MongoDB Atlas will let us
use a free 500 MB of MongoDB database and use it remotely. It is also
hosted in the cloud. This is the current trend of our industry and
acquiring skills that enables us to use cloud database is a real asset
nowadays.

After setting up your account, log into your account. Follow the steps
prompted by the website in creating your own cluster and
cluster/database users. Here is the checklist or steps in order to create
your own mongoDB database.

1. Build your first cluster.

2. Create your first database user.

3. Whitelist your IP address (in our case, the localhost:3001)

4. Connect your cluster.

We need to get the connection string of our database, so for step 4 we


just need to click the connect button of our created cluster as shown
below.

9 of 17 7/30/19, 2:49 AM
Let’s build a full stack MongoDB, React, Node an... https://medium.com/javascript-in-plain-english/full...

cluster connection

Then click “choose a connection method” at the bottom part of the


modal, select “Connect your Application”. Then, copy the string show
by the modal.

connection string

10 of 17 7/30/19, 2:49 AM
Let’s build a full stack MongoDB, React, Node an... https://medium.com/javascript-in-plain-english/full...

Paste this string uri in your server.js file. Find the dbRoute variable
and put the link with your credentials there as a string.

Now, back to our back end source code. We will now configure our
database, in order to do so, create a file named data.js. It should have
the following code inside it.

1 // /backend/data.js
2 const mongoose = require("mongoose");
3 const Schema = mongoose.Schema;
4
5 // this will be our data base's data structure
6 const DataSchema = new Schema(
7 {
8 id: Number,
9 message: String
10 },
11 { timestamps: true }
12 );
13
14 // export the new Schema so we could modify it using Node.js
15 module.exports = mongoose.model("Data", DataSchema);

“MongoDB, Baby”

We are almost DONE! Let’s just install our back end’s package and
modules and we are good to go. Just pass this line on your command
line.

npm i -S mongoose express body-parser morgan cors

11 of 17 7/30/19, 2:49 AM
Let’s build a full stack MongoDB, React, Node an... https://medium.com/javascript-in-plain-english/full...

Now, if we launch our back end using

node server.js

We can see in our console that it is ready and is listening on port


3001. Let’s go back to our front end and start creating the UIs needed
to dispatch actions unto our MongoDB + Node.JS + Express.JS
system.

Aww, yeah!!!!

Go back to /client/src/App.js and apply the following changes.

12 of 17 7/30/19, 2:49 AM
Let’s build a full stack MongoDB, React, Node an... https://medium.com/javascript-in-plain-english/full...

1 // /client/App.js
2 import React, { Component } from 'react';
3 import axios from 'axios';
4
5 class App extends Component {
6 // initialize our state
7 state = {
8 data: [],
9 id: 0,
10 message: null,
11 intervalIsSet: false,
12 idToDelete: null,
13 idToUpdate: null,
14 objectToUpdate: null,
15 };
16
17 // when component mounts, first thing it does is fetch all existing data in our db
18 // then we incorporate a polling logic so that we can easily see if our db has
19 // changed and implement those changes into our UI
20 componentDidMount() {
21 this.getDataFromDb();
22 if (!this.state.intervalIsSet) {
23 let interval = setInterval(this.getDataFromDb, 1000);
24 this.setState({ intervalIsSet: interval });
25 }
26 }
27
28 // never let a process live forever
29 // always kill a process everytime we are done using it
30 componentWillUnmount() {
31 if (this.state.intervalIsSet) {
32 clearInterval(this.state.intervalIsSet);
33 this.setState({ intervalIsSet: null });
34 }
35 }
36
37 // just a note, here, in the front end, we use the id key of our data object
38 // in order to identify which we want to Update or delete.
39 // for our back end, we use the object id assigned by MongoDB to modify
40 // data base entries

13 of 17 7/30/19, 2:49 AM
Let’s build a full stack MongoDB, React, Node an... https://medium.com/javascript-in-plain-english/full...

“React Rocks”

Lastly, we edit our front end’s package.json and add a proxy there to
point to the port where our back end is deployed.

1 {
2 "name": "client",
3 "version": "0.1.0",
4 "private": true,
5 "dependencies": {
6 "axios": "^0.18.0",
7 "react": "^16.5.0",
8 "react-dom": "^16.5.0",
9 "react-scripts": "1.1.5"
10 },
11 "scripts": {
12 "start": "react-scripts start",
13 "build": "react-scripts build",
14 "test": "react-scripts test --env=jsdom",
15 "eject": "react-scripts eject"
16 },
17 "proxy": "http://localhost:3001"
18 }

Remember, this is our front end’s package.json so this is included


inside the client directory. Edit that there.

There, all that’s left to do is to make it so that we can launch our back
end then our front end at the same time.

In order to do that go back to the main directory of our project and


type the following:

14 of 17 7/30/19, 2:49 AM
Let’s build a full stack MongoDB, React, Node an... https://medium.com/javascript-in-plain-english/full...

npm init -y
npm i -S concurrently

Edit the package.json of our main project’s directory. Change it as


follows.

1 {
2 "name": "fullstack_app",
3 "version": "1.0.0",
4 "description": "",
5 "main": "index.js",
6 "scripts": {
7 "start": "concurrently \"cd backend && node server.js\" \"cd client && npm start
8 },
9 "keywords": [],
10 "author": "",
11 "license": "ISC",
12 "dependencies": {
13 "concurrently": "^4.0.1"
14 }
15 }

Here, you can see under the “scripts” key, the “start” key makes use of
the package we just installed, the concurrently package. That package
enables us to run the back end code using:

node server.js

15 of 17 7/30/19, 2:49 AM
Let’s build a full stack MongoDB, React, Node an... https://medium.com/javascript-in-plain-english/full...

And the front end code using:

npm start

There’s a lot happening under the hood in able to do this, but for now,
we will just leave it be and be happy that it works! Now, to start our
app just go to the main directory of our project then type:

npm start

A browser will open that contains our app and voila! We have made
our own MERN (FULL STACK) app from scratch! Feel free to play
around with it. Use it as a sand box to grasp the different concepts of
both ends here.

Oh, and one more thing. Make sure to enable CORS on your browser
since we are calling our own APIs via our own machine. Here is a

As promise, here is the git repo.

That’s All Folks, cheers!

16 of 17 7/30/19, 2:49 AM
Let’s build a full stack MongoDB, React, Node an... https://medium.com/javascript-in-plain-english/full...

I hope that I have provided clear instructions and that I was able to
transfer as much knowledge as I can, to you, the reader.

If you found this useful, be sure to leave some claps! Oh, and share it
on your social platforms too! :)

JavaScript Mongodb React Expressjs Nodejs

17 of 17 7/30/19, 2:49 AM

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy