MERN Stack: A complete MERN guide - Part 2

Nur Islam
6 min readSep 29, 2022

--

This tutorial is all about the MERN stack. We’ll outline the basics of the MERN stack and demonstrate how to use it by developing a simple CRUD application from scratch.

To show how the MERN stack works, we’ll first configure the server side by connecting Node.js and Express.js to MongoDB on the backend. Then, we’ll create some APIs. After that, we’ll walk you through building the front end, using React to build our user interfaces. Once both are complete, we’ll connect the front end to the back end.

Meanwhile, we’ll cover the following topics

  • Database management with MongoDB
  • Building RESTful APIs with the MERN stack
  • Building the frontend
  • Setting up Create React App
  • Initial project structure
  • Frontend tasks and features
  • Adding feature components
  • Connecting the frontend and backend
  • Running the frontend and backend
  • Testing our MERN stack app in the browser

This demo is designed to highlight the MERN setup. The objective is to develop a simple project with the best possible structure so that you can use it as a boilerplate and elevate your MERN stack projects to meet industry standards.

Database management with MongoDB

Now it’s time to work on our MERN 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. Create one and follow the procedure. After creating an account, you will see something like this:

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:

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

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.

In this case, select the Connect Your Application section.

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

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:

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

Note: Replace <password> with your database password

// db.jsconst 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:

// app.jsconst 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:

$ npm i config

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

$ npm run app

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.

Building RESTful APIs with the MERN stack

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:

// routes/api/books.jsconst 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:

// models/Book.jsconst 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.

Congratulations! You have successfully completed this MERN stack tutorial part 2, read part 1 here and part 3 here.

You can visit my GitHub to see both the server-side and client-side portions of this MERN stack tutorial. You can also find the complete repo for our MERN stack example app on GitHub.

Originally published at https://blog.logrocket.com on February 26, 2021.

--

--