MERN stack A to Z: Part 1
Tags: featuredposts, react, node, javascript
Published: 2019-07-11 21:14:05

---
title: MERN stack A to Z: Part 1
published: true
tags: Featured Posts, react, node, javascript
canonical_url: https://blog.logrocket.com/mern-stack-a-to-z-part-1/
---

![](https://thepracticaldev.s3.amazonaws.com/i/ds38ffck01cqcub98cgz.jpg)

This tutorial is all about the MERN stack. We are going to explore this popular stack and how to use it by developing a simple CRUD (create, read, update, and delete) application from scratch.

Rather than focusing on the application itself, we will focus on the MERN setup. Though the project will be very simple, we will try to follow the best possible project structure to elevate it to an industry-standard level so that anyone can use this as a boilerplate project.

The phrase “MERN stack” refers to the following technologies:

- **MongoDB:** MongoDB is a cross-platform document-oriented database program
- **Express.js:** Express.js, or simply Express, is a web application framework for Node.js
- **React:** React is a JavaScript library for building user interfaces.
- **Node.js:** Node.js is an open-source, cross-platform JavaScript run-time environment that executes JavaScript code outside of a browser

To make this tutorial simple, I will break it into two parts:

- **Part 1:** In this part, we want to complete the server-side work. We’ll work with Node and Express and connect it with MongoDB. After that, we’ll create some APIs.
- **Part 2:** In the next section, we will focus on the frontend part with React to build our user interfaces. After that, we will connect our frontend to our backend.

> **Note:** The series will assume a basic understanding of Node.js, Express, MongoDB, and React.

[![LogRocket Free Trial Banner](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/f760c-1gpjapknnuyhu8esa3z0jga.png?resize=1200%2C280&ssl=1)](https://logrocket.com/signup/)

## Server setup with Express and Node

### npm package initialization

Our first task is to create a project folder. Enter the folder through the terminal, then run the following command:

```jsx
$ npm init
```

Now it will ask you some questions about package name, version, entry point, etc. Hit enter if you want to keep the default. After that, you will get something like this:

![Creating Our package.json File](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2019/07/npm-package.json-file-e1562600260796.png?resize=730%2C996&ssl=1)

Select **yes** and you are ready to go. It creates a file named `package.json`.

### Dependencies packages installation

Now, I would like to add some dependencies:

```jsx
$ npm i express mongoose body-parser bcryptjs validation
```

Type or copy the command above and hit the enter button. You will see something like this:

![Adding Project File Dependencies](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2019/07/adding-project-file-dependencies-e1562600284195.png?resize=730%2C191&ssl=1)

- **bcryptjs**  is a password hashing function designed by Niels Provos and David Mazières
- **body-parser** allows us to get the data throughout the request
- **express** is our main framework
- **mongoose**  is used to connect/interact with MongoDB
- **validation** (as its name implies) is used for validation

Now I want to add [nodemon](https://nodemon.io/) as a dev dependency. If you don’t want to add this, you can skip it — it’s optional.

```jsx
$ npm i -D nodemon
```

nodemon is a utility that will monitor for any changes in your source and automatically restart your server.

At that point, your `package.json` should look like this:

![package.json File With Dependencies](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2019/07/package.json-file-dependencies.png?resize=709%2C802&ssl=1)

### Setting the entry point

Now create a file named `app.js` for our entry point. You can create this from the project folder with the command below (on Mac):

```jsx
$ touch app.js
```

Then paste the code below:
```jsx
// app.js

const express = require('express');

const app = express();

app.get('/', (req, res) => res.send('Hello world!'));

const port = process.env.PORT || 8082;

app.listen(port, () => console.log(`Server running on port ${port}`));
```
Now, run the command

```jsx
$ node app
```

You will see **Server running on port 8082**. You can also check it from the browser: open the browser and enter `http://localhost:8082`.

At this point, if we change anything, we need to restart the server manually. But if we set up nodemon, then we don’t have to restart it every time; nodemon will watch if there is any change and restart the server automatically.

So what you need to do for that is a little change to the scripts in our `package.json` file. See below:
```jsx
// package.json

{
  "name": "mern_a_to_z",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "start": "node app.js",
    "app": "nodemon app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/nurislam03/MERN_A_to_Z.git"
  },
  "author": "Nur Islam",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/nurislam03/MERN_A_to_Z/issues"
  },
  "homepage": "https://github.com/nurislam03/MERN_A_to_Z#readme",
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "mongoose": "^5.5.15",
    "validation": "0.0.1"
  },
  "devDependencies": {
    "nodemon": "^1.19.1"
  }
}
```
So, now you can run your project using this command:

```jsx
$ npm run app
```

If you get any error at this point, then run the commands below:

```jsx
$ npm install
$ npm run app
```

You will see the following changes in your terminal if everything goes right:

![Running Project Successfully](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2019/07/running-project-successful.png?resize=728%2C235&ssl=1)

## Database management with MongoDB

Now it’s time to work on our database setup with MongoDB. For simplicity, we will use MongoDB Atlas.

### Creating an account for MongoDB Atlas

MongoDB Atlas is a fully managed cloud database developed by the same team that built MongoDB.

First, [you need an account](https://www.mongodb.com/cloud/atlas). Create one and follow the procedure. After creating an account, you will see something like this:

![MongoDB Atlas Homescreen](https://i1.wp.com/blog.logrocket.com/wp-content/uploads/2019/07/mongodb-homescreen-e1562599566295.png?resize=730%2C406&ssl=1)

Click on the **Project 0** section (top left) and you will see a button for creating a new project. Create a project and select the project.

Now, click on the **Build a Cluster** button from the project you have created. It will show you all the information. At the bottom, you will see a section called **Cluster Name** , click on that and enter a name for the database, then hit the **Create Cluster** button.

After two to three minutes, if everything goes well, you will find something like this:

![Creating A Cluster In MongoDB Atlas](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2019/07/creating-cluster-mongodb.png?resize=730%2C387&ssl=1)

Click on the **CONNECT** button and fill in the username and password form for your database.

![Setting Up Our Connection](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2019/07/setting-up-connection-mongodb-atlas-e1562599847264.png?resize=730%2C574&ssl=1)

Now hit the **Create MongoDB User** button. You can also choose either your current IP address or a different IP address, it’s up to you.

Now, if you follow the **CONNECT** button or the **Choose a connection method** button, you will see some different methods. Select accordingly.

![Connection Methods Options](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2019/07/connection-method-options-mongodb-e1562600007239.png?resize=730%2C645&ssl=1)

In this case, select the **Connect Your Application** section.

Now you will get your database link, which we will use in our next step.

![Connection String Output](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2019/07/connection-string-output-mongodb.png?resize=730%2C705&ssl=1)

Our database is ready — now we need to add it to our project.

Inside the project folder, create another folder named `config` and inside it create two files named `default.json` and `db.js`. Add the following code:
```jsx
// default.json

{
  "mongoURI":
    "mongodb+srv://mern123:<password>@mernatoz-9kdpd.mongodb.net/test?retryWrites=true&w=majority"
}
 /* Replace <password> with your database password */

/* ------------------------------------------------------------------ */
// db.js

const mongoose = require('mongoose');
const config = require('config');
const db = config.get('mongoURI');

const connectDB = async () => {
  try {
    await mongoose.connect(
      db,
      {
        useNewUrlparser: true
      }
    );

    console.log('MongoDB is Connected...');
  } catch (err) {
    console.error(err.message);
    process.exit(1);
  }
};

module.exports = connectDB;
```
**NOTE:** We need a little change in our `app.js` file to connect to the database. Update your `app.js` with this:
```jsx
// app.js

const express = require('express');
const connectDB = require('./config/db');

const app = express();

// Connect Database
connectDB();

app.get('/', (req, res) => res.send('Hello world!'));

const port = process.env.PORT || 8082;

app.listen(port, () => console.log(`Server running on port ${port}`));
```
We need another dependency package called `config` for the global variable to run our project. Use the following command to install it to the project:

```jsx
$ npm i config
```

Now, you can run the project using the following command:

```jsx
$ npm run app
```

![Successfully Connected Server](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2019/07/successfully-connected-server.png?resize=720%2C253&ssl=1)

Great! So far we are on the right track. Our database is successfully connected. Now time to complete the route setup, and after that, we will see how to create RESTful APIs.

## RESTful APIs

Create a folder named `routes`. In it, create another folder named `api`, which will hold all our APIs.

Inside the `api` folder, create a file named `books.js`. We will create some APIs here to show how it works in a moment.

Now update your `books.js` with the following code:
```jsx
// routes/api/books.js

const express = require('express');
const router = express.Router();

// Load Book model
const Book = require('../../models/Book');

// @route GET api/books/test
// @description tests books route
// @access Public
router.get('/test', (req, res) => res.send('book route testing!'));

// @route GET api/books
// @description Get all books
// @access Public
router.get('/', (req, res) => {
  Book.find()
    .then(books => res.json(books))
    .catch(err => res.status(404).json({ nobooksfound: 'No Books found' }));
});

// @route GET api/books/:id
// @description Get single book by id
// @access Public
router.get('/:id', (req, res) => {
  Book.findById(req.params.id)
    .then(book => res.json(book))
    .catch(err => res.status(404).json({ nobookfound: 'No Book found' }));
});

// @route GET api/books
// @description add/save book
// @access Public
router.post('/', (req, res) => {
  Book.create(req.body)
    .then(book => res.json({ msg: 'Book added successfully' }))
    .catch(err => res.status(400).json({ error: 'Unable to add this book' }));
});

// @route GET api/books/:id
// @description Update book
// @access Public
router.put('/:id', (req, res) => {
  Book.findByIdAndUpdate(req.params.id, req.body)
    .then(book => res.json({ msg: 'Updated successfully' }))
    .catch(err =>
      res.status(400).json({ error: 'Unable to update the Database' })
    );
});

// @route GET api/books/:id
// @description Delete book by id
// @access Public
router.delete('/:id', (req, res) => {
  Book.findByIdAndRemove(req.params.id, req.body)
    .then(book => res.json({ mgs: 'Book entry deleted successfully' }))
    .catch(err => res.status(404).json({ error: 'No such a book' }));
});

module.exports = router;
```
### Database model

In order to interact with our database, we need to create a model for each of our resources. So, create a folder called `models` in the root, and inside the `models` folder, create a file called `Book.js` and update it with this:
```jsx
// models/Book.js

const mongoose = require('mongoose');

const BookSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true
  },
  isbn: {
    type: String,
    required: true
  },
  author: {
    type: String,
    required: true
  },
  description: {
    type: String
  },
  published_date: {
    type: Date
  },
  publisher: {
    type: String
  },
  updated_date: {
    type: Date,
    default: Date.now
  }
});

module.exports = Book = mongoose.model('book', BookSchema);
```
Run the project to see if everything is fine at this point, and you can test all the APIs through Postman (note that before testing APIs using Postman, you need to run the project first). You can [download Postman here](https://www.getpostman.com/).

## Conclusion

So far, so good! We have set up our backend successfully. Now we need to work with our frontend part, where we will be using React to build user interfaces. Check back soon for Part 2, and in the meantime, you can find the [GitHub repo for the project here](https://github.com/nurislam03/MERN_A_to_Z).

* * *

## Plug: [LogRocket](https://logrocket.com/signup/), a DVR for web apps

[![LogRocket Dashboard Free Trial Banner](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/1d0cd-1s_rmyo6nbrasp-xtvbaxfg.png?resize=1200%2C677&ssl=1)](https://logrocket.com/signup/)

[LogRocket](https://logrocket.com/signup/) is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.

[Try it for free](https://logrocket.com/signup/).

***

The post [MERN stack A to Z: Part 1](https://blog.logrocket.com/mern-stack-a-to-z-part-1/) appeared first on [LogRocket Blog](https://blog.logrocket.com).