React Node.js MongoDB CRUD Example – MERN Stack

Reactjs Nodejs MongoDB CRUD Example

Tutorial: “React Node.js MongoDB CRUD Example – MERN Stack Application”

In the tutorial, I introduce how to build an “React.js Nodejs CRUD MongoDB Example” project with the help of Ajax to POST/GET/PUT/DELETE requests with step by step coding examples:

– Nodejs project produces CRUD RestAPIs with MongoDB database using the supporting of Mongoose ODM.
– React.js project will consume the Nodejs CRUD RestAPIs by Ajax then show up on Reactjs component’s views.

Related posts:


– I draw a fullstack overview Diagram Architecture from React.js Frontend to MongoDB database through Nodejs RestAPI backend.
– Develop Nodejs CRUD RestAPIs with the supporting of Mongoose ODM.
– Implement Reactjs CRUD application with Ajax fetching APIs to do CRUD request (Post/Get/Put/Delete) to Nodejs Backend APIs.
– I create a testsuite with a number of integrative testcases with CRUD RestAPI requests from Reactjs to do CRUD requests to Nodejs RestAPIs Server and save/retrieve data to MongoDB database.

What will we do?


Overall Architecture System: React Node.js MongoDB CRUD Example

React.js Nodejs MongoDB Diagram Architecture
React.js Nodejs MongoDB Diagram Architecture
  • We build a backend: Nodejs CRUD Application with MongoDB that provides RestAPIs for POST/GET/PUT/DELETE data entities and store them in MongoDB database.
  • We implement React.js CRUD Application that use Ajax to interact (call/receive requests) with Nodejs CRUD application and display corresponding data in Reactjs Component.

Nodejs MongoDB CRUD Design Application – React Node.js MongoDB CRUD Example

Nodejs MongoDB CRUD Example - React Node.js MongoDB CRUD Example
Nodejs MongoDB CRUD Example

In the tutorial “React Node.js MongoDB CRUD Example”, with Nodejs Backend, We have 4 main blocks for the application:

  • For building RestAPIs in Nodejs application, we use Express framework.
  • For interacting with database MongoDB, we use Mongoose ODM.
  • We define APIs URL in router.js file
  • We implement how to process each API URL in controller.js file
  • We use Bootstrap and JQuery Ajax to implement frontend client.

Reactjs CRUD Application Design – React Node.js MongoDB CRUD Example

Reactjs CRUD RestAPI Application Frontend Architecture Diagram - React Node.js MongoDB CRUD Example
Reactjs CRUD RestAPI Application Frontend Architecture Diagram

– Reactjs CRUD Application is designed with 2 main layers:

  • React.js components let you split the UI into independent, reusable pieces, and think about each piece in isolation.
  • Ajax is used by Reactjs component to fetch (post/put/get/delete) data from remote restapi by http request

Reactjs CRUD Application defines 5 components:

  • Home.js is used serve as the landing page for your app.
  • AppNavbar.js is used to establish a common UI feature between components.
  • CustomerList.js is used to show all customers in the web-page
  • CustomerEdit.js is used to modify the existed customer
  • App.js uses React Router to navigate between components.

Integrative Project Goal – React Node.js MongoDB CRUD Example

Reactjs Home page:

Project Goal Home Page - React Node.js MongoDB CRUD Example
Project Goal Home Page

Reactjs List all data:

Project Goal Customer List - React Node.js MongoDB CRUD Example
Project Goal Customer List

Reactjs add data:

Project Goal Reactjs Add a Customer through Nodejs RestAPI - React Node.js MongoDB CRUD Example
Project Goal Reactjs Add a Customer through Nodejs RestAPI

Reactjs update data:

Project Goal Reactjs Update Customer through Nodejs RestAPI to MongoDB database
Project Goal Reactjs Update Customer through Nodejs RestAPI to MongoDB database

Reactjs delete a customer, check the Customer List after deleting:

Project Goal - Reactjs show List Customer after Delete successfully - React Node.js MongoDB CRUD Example
Project Goal – Reactjs show List Customer after Delete successfully

Check MongoDB Database after do CRUD operations:

Check MongDB after doing CRUD operations - React Node.js MongoDB CRUD Example
Check MongDB after doing CRUD operations

How to Integrate Reactjs with Nodejs? – React Node.js MongoDB CRUD Example

For starting to integrate Reactjs with Nodejs project, I recommend you a previous post with detail steps to pratice:

How to Integrate Reactjs with Nodejs Tutorial

Nodejs MongoDB CRUD RestAPIs Example – Backend Development

Now it’s time for building the “Nodejs MongoDB CRUD RestAPIs Example” project with a set of simple steps:

Let’s go!

Create Nodejs MongoDB project – React Node.js MongoDB CRUD Example

Before creating a Nodejs project, we need to confirm that the Nodejs and npm had been installed in your computer development by cmd: node -v and npm -v

Check Nodejs environment for development
Check Nodejs environment for development

If these commandlines are not recognized by command prompt, it means you need to install them by visit the https://nodejs.org/en/ site and download installed package and do the nodejs setup for development later.

Now starting development! Create a folder and named it as Nodejs-Reactjs-MongoDB, go inside the folder, open a cmd and initiate a Nodejs project by cmd npm init. After all, a package.json file is created as below content:

{
  "name": "nodejs-express-mongodb-example",
  "version": "1.0.0",
  "description": "Nodejs CRUD restapi MongoDB Example",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "loizenai"
  },
  "keywords": [
    "Nodejs",
    "MongoDB",
    "CRUD",
    "RestAPI"
  ],
  "author": "https://loizenai.com",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mongoose": "^5.10.7",
  }
}

For coding Editor, we use friendly Visual Studio Code to write code and debug Nodejs project. For the tutorial, We will create a project with below structure:

Nodejs-MongoDB-Crud-Project-Structure
Nodejs-MongoDB-Crud-Project-Structure
  1. a file mongodb.config.js is used to define MongoDB database configuration with Mongoose ODM
  2. a file customer.model.js is used to define a Mongoose model mapped with corresponding MongoDB database table schema.
  3. a file router.js is used to define all Express RestAPI URLs
  4. a file controller.js is used to implement detail logic code to process each incoming request
  5. a file server.js is used to implement a Nodejs Web server

To development a Nodejs CRUD MongoDB project, we need a set of packages to handle the full stack of the web backend proccessing, they includes Express framework, Cors, Body Parse, and Mongoose ODM.

$npm install --save express cors body-parser mongoose

Nodejs MongoDB Database Configuration – React Node.js MongoDB CRUD Example

In the tutorial, for the main setting between MongoDB database and Mongoose ODM, we define a file mongodb.config.js as below code:

module.exports = {
  url: 'mongodb+srv://loizenai:12345@cluster0.uhqpv.mongodb.net/loizenaidb?retryWrites=true&w=majority'
}

Define Nodejs Mongoose Model

In the tutorial “React Node.js MongoDB CRUD Example”, We need define a Mongoose ODM Model to represent a table in the database. So here is the customer.model.js code:

const mongoose = require('mongoose');
 
const CustomerSchema = mongoose.Schema({
    firstname: String,
    lastname: String,
    address: String,
    age: { 
      type: Number, 
      min: 18, 
      max: 65, 
      required: true 
    },
    copyrightby: {
      type: String,
      default: 'https://loizenai.com'
    }
});

module.exports = mongoose.model('Customer', CustomerSchema);

We create a Mongoose Customer model with 6 attributes for mapping with all corresponding customers table’s columns:

  1. id attribute is a primary key with Int type (in database)
  2. firstname attribute has Mongoose.STRING type mapping with the firstname column in customers table with varchar type
  3. lastname attribute has Mongoose.STRING type mapping with the lastname column in customers table with varchar type
  4. address attribute has Mongoose.STRING type mapping with the lastname column in customers table with varchar type
  5. age attribute has Mongoose.INTEGER type mapping with the age column in customers table with int type
  6. copyrightby attribute has Mongoose.STRING type mapping with the copyrightby column in customers table with varchar type and having default value is https://loizenai.com

Define Express RestAPIs Router – POST/GET/PUT/DELETE

In the tutorial “React Node.js MongoDB CRUD Example”, We define 5 APIs:

  • /api/customer (with POST method) is used to Post a customer to MongoDB database
  • /api/customer/:id (with GET method) is used to retrieve a customer from MongoDB database with a given id
  • /api/customers (with GET method) is used to retrieve all customers from MongoDB database
  • /api/customer (with PUT method) is used to update a customer from MongoDB database
  • /api/customer/:id (with DELETE method) is used to remove a customer from MongoDB database

Coding:

module.exports = function(app) {
 
  var customers = require('../controllers/customer.controller.js');

  app.post('/api/customer', customers.createCustomer);
  app.get('/api/customer/:id', customers.getCustomer);
  app.get('/api/customers', customers.customers);
  app.put('/api/customer', customers.updateCustomer);
  app.delete('/api/customer/:id', customers.deleteCustomer);
}

Node.js Express Implement RestAPIs Controller

For processing Post/Get/Put/Delete RestAPI requests, we implement controller.js with 5 functions:

  • exports.createCustomer = (req, res) is used to create a new Customer (post request processing)
  • exports.getCustomer = (req, res) is used to retrieve a Customer with a given id from MongoDB database(get request)
  • exports.customers = async (req, res) is used to retrieve all customers
  • exports.updateCustomer = async (req, res) is used to update a customer from MongoDB database
  • exports.deleteCustomer = async (req, res) is used to delete a customer from MongoDB database
Nodejs Post request – Add a data to MongoDB
exports.createCustomer = (req, res) => {

    const customer = new Customer({
                          firstname: req.body.firstname,
                          lastname: req.body.lastname,
                          age: req.body.age,
                          address: req.body.address,
                        });
 
    // Save a Customer in the MongoDB
    customer.save().then(data => {
                    res.status(200).json(data);
                }).catch(err => {
                    res.status(500).json({
                      message: "Fail!",
                      error: err.message
                    });
                });
};

exports.createCustomer = (req, res) gets a posting customer’s info via request.body object. Then it uses Mongoose to save the customer object to database. After done, it returns a successfully posting message. Otherwise, a error message will be returned.

Nodejs Express RestAPI Get request – retrieve a single data from MongoDB

exports.getCustomer = (req, res) => {
  Customer.findById(req.params.id).select('-__v')
      .then(customer => {
        res.status(200).json(customer);
      }).catch(err => {
          if(err.kind === 'ObjectId') {
              return res.status(404).send({
                  message: "Customer not found with id " + req.params.id,
                  error: err
              });                
          }
          return res.status(500).send({
              message: "Error retrieving Customer with id " + req.params.id,
              error: err
          });
      });
};

exports.getCustomer = (req, res) retrieves a customer data from MongoDB database with a given id by using Mongoose ODM. After done, it returns a customer object to client. Otherwise, a error message will be returned.

Node.js Express RestAPI Get request – retrieve all data from MongoDB database

exports.customers = (req, res) => {
    Customer.find().select('-__v').then(customerInfos => {
          res.status(200).json(customerInfos);
        }).catch(error => {
          // log on console
          console.log(error);

          res.status(500).json({
              message: "Error!",
              error: error
          });
        });
};

The function exports.customers = (req, res) retrieves all Customer objects from MongoDB database.

Node.js Express RestAPI Delete request – delete a data from MongoDB with a given id

exports.deleteCustomer = (req, res) => {
    let customerId = req.params.id

    Customer.findByIdAndRemove(customerId).select('-__v -_id')
        .then(customer => {
            if(!customer) {
              res.status(404).json({
                message: "Does Not exist a Customer with id = " + customerId,
                error: "404",
              });
            }
            res.status(200).json({});
        }).catch(err => {
            return res.status(500).send({
              message: "Error -> Can NOT delete a customer with id = " + customerId,
              error: err.message
            });
        });
};

The function exports.deleteCustomer = async (req, res) finds a Customer by a given id. If the customer is found, it will be deleted by destroy() function and return back client a successfully message with 200 status code. Otherwise, an error message is returned.

Node.js Express Put request – update a data from MongoDB – React Node.js MongoDB CRUD Example

In the tutorial “React Node.js MongoDB CRUD Example”, We create a Nodejs RestAPIs for put request as below code:

exports.updateCustomer = (req, res) => {
    // Find customer and update it
    Customer.findByIdAndUpdate(
                      req.body._id, 
                      {
                        firstname: req.body.firstname,
                        lastname: req.body.lastname,
                        age: req.body.age,
                        address: req.body.address
                      }, 
                        {new: true}
                    ).select('-__v')
        .then(customer => {
            if(!customer) {
                return res.status(404).send({
                    message: "Error -> Can NOT update a customer with id = " + req.params.id,
                    error: "Not Found!"
                });
            }

            res.status(200).json(customer);
        }).catch(err => {
            return res.status(500).send({
              message: "Error -> Can not update a customer with id = " + req.params.id,
              error: err.message
            });
        });
};

The function exports.updateCustomer = async (req, res) finds a customer object by a given id. If the customer is found, we change the customer attributes with new values retrieving from request.body object. After done, a successfully message will be returned. Otherwise an error message will be returned.

Create Nodejs Server.js – React Node.js MongoDB CRUD Example

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json())

// Configuring the database
const dbConfig = require('./app/config/mongodb.config.js');
const mongoose = require('mongoose');

const Customer = require('./app/models/customer.model.js');
 
mongoose.Promise = global.Promise;
 
// Connecting to the database
mongoose.connect(dbConfig.url, { useNewUrlParser: true, useUnifiedTopology: true })
    .then(async () => {
        console.log("Successfully connected to MongoDB.");   
        const customers = [
            { firstname: 'Jack', lastname: 'Smith', 
                      age: 23, address: '374 William S Canning Blvd'},
            { firstname: 'Adam', lastname: 'Johnson', 
                      age: 31, address: 'Fall River MA 2721. 121 Worcester Rd'},
            { firstname: 'Dana', lastname: 'Bay', 
                      age: 46, address: 'Framingham MA 1701. 677 Timpany Blvd'},
          ]

        for(let i=0; i<customers.length; i++){

            const customer = new Customer({
                firstname: customers[i].firstname,
                lastname: customers[i].lastname,
                age: customers[i].age,
                address: customers[i].address
              });

            // Save a Customer in the MongoDB
            await customer.save();
        }
    }).catch(err => {
        console.log('Could not connect to MongoDB.');
        process.exit();
    });

require('./app/routes/customer.router.js')(app);
// Create a Server
var server = app.listen(8080, function () { 
  var host = server.address().address
  var port = server.address().port
 
  console.log("App listening at http://%s:%s", host, port) 
})

How does the server.js file work?

server.js file will create a Nodejs server’s instance listening at port 8080 and also initiate a MongoDB document customers with 3 records.

const express = require('express');
const app = express();
...
const server = app.listen(8080, function () {
 
  let host = server.address().address
  let port = server.address().port
 
  console.log("App listening at http://%s:%s", host, port); 
})

– For parsing body of requests, we need use body-parser dependency, some below lines of code will be added to server.js file:

...
var bodyParser = require('body-parser');
...
app.use(bodyParser.json());
...
const server = app.listen(8080, function () {
...

We define all RESTAPI URLs in a file router.js and then need attach it with the Express Application:

...
require('./app/routes/customer.router.js')(app);
...
const server = app.listen(8080, function () {
...

Backend Testing – Nodejs MongoDB CRUD RestAPIs testsuite

MongoDB database:

Check MongoDB documents - React Node.js MongoDB CRUD Example
Check MongoDB documents

1. Testcase 1 – Node.js Express RestAPI Get all Customers:

– Nodejs retrieves all customers from MongoDB database:

Nodejs get request - retrieve all documents from MongoDB - React Node.js MongoDB CRUD Example
Nodejs get request – retrieve all documents from MongoDB

2. Testcase 2 – Node.js Express RestAPI Post request – Create a Customer:

– Nodejs posts a new customer to MongoDB database:

Nodejs Post request - add a new data to MongoDB
Nodejs Post request – add a new data to MongoDB

3. Testcase 3 – Node.js Express RestAPI PUT request – Update a Customer:

– Nodejs updates a customer from MongoDB database:

Nodejs Put request - update data to MongoDB - React Node.js MongoDB CRUD Example
Nodejs Put request – update data to MongoDB

4. Testcase 4 – Node.js Express RestAPI Delete request – Delete a Customer:

– Nodejs delete a Customer from MongoDB database:

Nodejs Delete request - remove a document from MongoDB - React Node.js MongoDB CRUD Example
Nodejs Delete request – remove a document from MongoDB

React.js CRUD Application Overview with Node.js RestAPIs

React.js project structure
React.js project structure
Reactjs CRUD RestAPI Application Frontend Architecture Diagram - React Node.js MongoDB CRUD Example
Reactjs CRUD RestAPI Application Frontend Architecture Diagram

For more details, we go back to the session: Reactjs CRUD Application Overview with Nodejs RestAPIs

How to build Reactjs Application? – React Node.js MongoDB CRUD Example

We build a Reactjs Application that fetchs data from MongoDB database through MongoDB RestAPI with 5 UI components. Step to do:
– Setup Reactjs Application
– Build Reactjs Navigation Bar component
– Build Reactjs Home page component
– Build Reactjs CustomerList Component
– Build Reactjs CustomerEdit Component
– Update Reactjs App.js Component with Router

Setup Reactjs Application with Bootstrap – React Node.js MongoDB CRUD Example

Create React App is a command line utility that generates React projects for you. It’s a convenient tool because it also offers commands that will build and optimize your project for production.
The create-react-app will set up everything you need to run a React application.

– Create a new project in the app directory with Yarn.

yarn create react-app app

Project Structure:

Start Setup React project structure - React Node.js MongoDB CRUD Example
Start Setup React project structure

More details you can see at: Create Reactjs Project

After the app creation process completes, navigate into the app directory and install Bootstrap, cookie support for React, React Router, and Reactstrap.

Reactstrap: This library contains React Bootstrap 4 components that favor composition and control. The library does not depend on jQuery or Bootstrap javascript.
– React Router: Components are the heart of React’s powerful, declarative programming model. React Router is a collection of navigational components that compose declaratively with your application.

cd app
yarn add bootstrap@4.1.3 react-cookie@3.0.4 react-router-dom@4.3.1 reactstrap@6.5.0

Build Application Navigation Bar Component – React Node.js MongoDB CRUD Example

import React, { Component } from 'react';
import { Collapse, Nav, Navbar, NavbarBrand, NavbarToggler, NavItem, NavLink } from 'reactstrap';
import { Link } from 'react-router-dom';

export default class AppNavbar extends Component {
  constructor(props) {
    super(props);
    this.state = {isOpen: false};
    this.toggle = this.toggle.bind(this);
  }

  toggle() {
    this.setState({
      isOpen: !this.state.isOpen
    });
  }

  render() {
    return <Navbar color="dark" dark expand="md">
      <NavbarBrand tag={Link} to="/">Home</NavbarBrand>
      <NavbarToggler onClick={this.toggle}/>
      <Collapse isOpen={this.state.isOpen} navbar>
        <Nav className="ml-auto" navbar>
          <NavItem>
            <NavLink
              href="https://loizenai.com">loizenai.com</NavLink>
          </NavItem>
          <NavItem>
            <NavLink href="https://github.com/loizenai">GitHub</NavLink>
          </NavItem>
        </Nav>
      </Collapse>
    </Navbar>;
  }
}

Create Reactjs Home Page Component – React Node.js MongoDB CRUD Example

import React, { Component } from 'react';
import './App.css';
import AppNavbar from './AppNavbar';
import { Link } from 'react-router-dom';
import { Button, Container } from 'reactstrap';

class Home extends Component {
  render() {
    return (
      <div>
        <AppNavbar/>
        <Container fluid>
          <Button color="link"><Link to="/customers">Manage Customer List</Link></Button>
        </Container>
      </div>
    );
  }
}

export default Home;

Build Reactjs CustomerList Component

Project Goal Customer List
Project Goal Customer List

– CustomerList Component will fetch a list of customers from Nodejs RestAPI api/customers and then shows all of them on a Bootstrap table.
– The CustomerList has 3 buttons:

  • Add Customer & Edit are used to link to a url /customers/new that will map with CustomerEdit component
  • Delete button is used to remove a Customer entity from MongoDB data based on a given id through an async function remove(id) that will do a fetch request with DELETE method to Nodejs RestAPI.

Detail coding:

import React, { Component } from 'react';
import { Button, ButtonGroup, Container, Table } from 'reactstrap';
import AppNavbar from './AppNavbar';
import { Link } from 'react-router-dom';

class CustomerList extends Component {

  constructor(props) {
    super(props);
    this.state = {customers: [], isLoading: true};
    this.remove = this.remove.bind(this);
  }

  componentDidMount() {
    this.setState({isLoading: true});

    fetch('api/customers')
      .then(response => response.json())
      .then(data => this.setState({customers: data, isLoading: false}));
  }

  async remove(id) {
    await fetch(`/api/customer/${id}`, {
      method: 'DELETE',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    }).then(() => {
      let updatedCustomers = [...this.state.customers].filter(i => i.id !== id);
      this.setState({customers: updatedCustomers});
    });
  }

  render() {
    const {customers, isLoading} = this.state;

    if (isLoading) {
      return <p>Loading...</p>;
    }

    const customerList = customers.map(customer => {
      return <tr key={customer.id}>
        <td style={{whiteSpace: 'nowrap'}}>{customer.firstname}</td>
        <td>{customer.lastname}</td>
        <td>{customer.age}</td>
        <td>{customer.address}</td>
        <td><a href={customer.copyright}>{customer.copyright}</a></td>
        <td>
          <ButtonGroup>
            <Button size="sm" color="primary" tag={Link} to={"/customers/" + customer.id}>Edit</Button>
            <Button size="sm" color="danger" onClick={() => this.remove(customer.id)}>Delete</Button>
          </ButtonGroup>
        </td>
      </tr>
    });

    return (
      <div>
        <AppNavbar/>
        <Container fluid>
          <div className="float-right">
            <Button color="success" tag={Link} to="/customers/new">Add Customer</Button>
          </div>
          <h3>Customer List</h3>
          <Table className="mt-4">
            <thead>
              <tr>
                <th width="20%">Firstname</th>
                <th width="20%">Lastname</th>
                <th width="10%">Age</th>
                <th>Address</th>
                <th>Copyrightby</th>
                <th width="10%">Actions</th>
              </tr>
            </thead>
            <tbody>
            {customerList}
            </tbody>
          </Table>
        </Container>
      </div>
    );
  }
}

export default CustomerList;

Build Reactjs CustomerEdit Component

Project Goal Reactjs Update Customer through Nodejs RestAPI to MongoDB database
Project Goal Reactjs Update Customer through Nodejs RestAPI to MongoDB database

We create a React FORM to Put/Post data to MongoDB database through Nodejs RestAPI by using a fetch (PUT/POST) function:

  async handleSubmit(event) {
    event.preventDefault();
    const {item} = this.state;

    await fetch('/api/customer', {
      method: (item.id) ? 'PUT' : 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(item),
    });
    this.props.history.push('/customers');
  }

After FORM submition, React Application will come back to a CustomerList component by using a coding-line:

this.props.history.push('/customers');

– Full coding:

import React, { Component } from 'react';
import { Link, withRouter } from 'react-router-dom';
import { Button, Container, FORM, FORMGroup, Input, Label } from 'reactstrap';
import AppNavbar from './AppNavbar';

class CustomerEdit extends Component {

  emptyCustomer = {
    firstname: '',
    lastname: '',
    age: '',
    address: '',
    copyrigtby: ''
  };

  constructor(props) {
    super(props);
    this.state = {
      item: this.emptyCustomer
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  async componentDidMount() {
    if (this.props.match.params.id !== 'new') {
      const customer = await (await fetch(`/api/customer/${this.props.match.params.id}`)).json();
      this.setState({item: customer});
    }
  }

  handleChange(event) {
    const target = event.target;
    const value = target.value;
    const name = target.name;
    let item = {...this.state.item};
    item[name] = value;
    this.setState({item});
  }

  async handleSubmit(event) {
    event.preventDefault();
    const {item} = this.state;

    await fetch('/api/customer', {
      method: (item.id) ? 'PUT' : 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(item),
    });
    this.props.history.push('/customers');
  }

  render() {
    const {item} = this.state;
    const title = <h2>{item.id ? 'Edit Customer' : 'Add Customer'}</h2>;

    return <div>
      <AppNavbar/>
      <Container>
        {title}
        <FORM onSubmit={this.handleSubmit}>
          <FORMGroup>
            <Label for="firstname">Firstname</Label>
            <Input type="text" name="firstname" id="firstname" value={item.firstname || ''}
                   onChange={this.handleChange} autoComplete="firstname"/>
          </FORMGroup>
          <FORMGroup>
            <Label for="lastname">Lastname</Label>
            <Input type="text" name="lastname" id="lastname" value={item.lastname || ''}
                   onChange={this.handleChange} autoComplete="lastname"/>
          </FORMGroup>          
          <FORMGroup>
            <Label for="age">Age</Label>
            <Input type="text" name="age" id="age" value={item.age || ''}
                   onChange={this.handleChange} autoComplete="age"/>
          </FORMGroup>
          <FORMGroup>
            <Label for="address">Address</Label>
            <Input type="text" name="address" id="address" value={item.address || ''}
                   onChange={this.handleChange} autoComplete="address"/>
          </FORMGroup>
          <FORMGroup>
            <Button color="primary" type="submit">Save</Button>{' '}
            <Button color="secondary" tag={Link} to="/customers">Cancel</Button>
          </FORMGroup>
        </FORM>
      </Container>
    </div>
  }
}

export default withRouter(CustomerEdit);

Edit Reactjs App.js Component

App.js uses React Router to navigate between components.

  • path “/” is mapped with Home component
  • path “/customers” is mapped with CustomerList component
  • path “customers/:id” is mapped with CustomerEdit component
import React, { Component } from 'react';
import './App.css';
import Home from './Home';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import CustomerList from './CustomerList';
import CustomerEdit from './CustomerEdit';

class App extends Component {
  render() {
    return (
      <Router>
        <Switch>
          <Route path='/' exact={true} component={Home}/>
          <Route path='/customers' exact={true} component={CustomerList}/>
          <Route path='/customers/:id' component={CustomerEdit}/>
        </Switch>
      </Router>
    )
  }
}

export default App;

Add a Proxy Setting for calling RestAPIs

To proxy from /api to http://localhost:8080/api, add a proxy setting to app/package.json.

"scripts": {...},
"proxy": "http://localhost:8080",

Integrative Testing: Reactjs Application with Nodejs CRUD RestAPIs + MongoDB

– Run Nodejs project, check MongoDB database:

Check MongoDB documents
Check MongoDB documents

– Start Reactjs Application by cmd: yarn start.

Testcase 1: Reactjs Post request – Post data to MongoDB through Nodejs RestAPI

Project Goal Reactjs Add a Customer through Nodejs RestAPI
Project Goal Reactjs Add a Customer through Nodejs RestAPI

Testcase 2: Reactjs Put request – Put data to MongoDB through Nodejs RestAPI

Project Goal Reactjs Update Customer through Nodejs RestAPI to MongoDB database
Project Goal Reactjs Update Customer through Nodejs RestAPI to MongoDB database

Testcase 3: Reactjs Fetch request – Get All data from MongoDB through Nodejs RestAPI

Project Goal - List Customer after update
Project Goal – List Customer after update

Testcase 4: Reactjs Delete request – Delete an entity from MongoDB through Nodejs RestAPI

Delete a Customer with id=2, check the CustomerList after successfully:

Project Goal - Reactjs show List Customer after Delete successfully
Project Goal – Reactjs show List Customer after Delete successfully

– Check MongoDB database after doing all CRUD operations:

Check MongDB after doing CRUD operations
Check MongDB after doing CRUD operations

Further Reading

Related posts:


Sourcecode – Nodejs React.js CRUD Example (React.js + Nodejs + MongoDB)

– Full Sourcecode: React.js + Nodejs + MongoDB – Nodejs React.js CRUD Example

1. Reactjs

Reactjs-Nodejs-MongoDB-CRUD-Example

2. Nodejs RestAPI

Nodejs-Reactjs-MongoDB-CRUD-Example

– Github Sourcecode:

1. Reactjs.

Reactjs – Github

2. Nodejs RestAPI:

Nodejs RestAPI – Github

23 thoughts on “React Node.js MongoDB CRUD Example – MERN Stack”

  1. Awesome! Its in fact awesome article, I have got much clear idea regarding from this piece of writing. Bert Gene Slavic

Leave a Reply

Your email address will not be published. Required fields are marked *