How to save React form data in Mongo Database

Relational databases like MySQL are theoretically the database of choice. However, NoSQL databases like MongoDB have gained popularity due to their flexible structure in data storage and their ability to save and extract data quickly.

These databases provide an alternative query language that you can seamlessly integrate with modern web and mobile applications. Here's how to save React data in a MongoDB database.

What is NoSQL Database?

NoSQL stands for Not only SQL, a non-relational database. This is the type of database that does not rely on the traditional model. It has no defined row structure and can save data in different formats. That makes it flexible and extensible.

The main difference between NoSQL and relational databases is that instead of having rows and columns, NoSQL databases store data in a dynamically structured document.

How to save React form data in Mongo Database Picture 1

Set up a MongoDB database

MongoDB is the most popular database. It is an open source database that stores data in a JSON-like document (table) form in a collection.

Here is an example of a simple MongoDB document structure:

{   FirstName: 'Andrew',   Role: 'Backend Developer' }

To get started, you first need to set up a MongoDB database. Once you have finished configuring MongoDB, open the MongoDB Compass app. Then, click the New Connection button to create a connection with the local Mongo server running.

Provide the connection URL and its name, then press Save & Connect .

How to save React form data in Mongo Database Picture 2

Finally, click the Create Database button , enter the database name and give the collection a name.

How to save React form data in Mongo Database Picture 3

Create React client

To quickly start a React application, create the project directory on the local machine, change the directory and run the terminal commands below to create and launch the server programming:

npx create-react-app my-app cd my-app npm start

Next, install Axios. This package will allow you to send HTTP queries to the Express.js backend server to store data in the MongoDB database.

npm install axios

Create a test form to collect user data

Open the file src/App.js , delete the boilerplate React code and replace it with:

import './App.css'; import React, { useState } from 'react'; import Axios from 'axios'; function App() {   const [name, setName] = useState("")   const [role, setRole] = useState("")   const handleSubmit = (e) => {       e.preventDefault();       Axios.post('http://localhost:4000/insert', {           fullName: name,           companyRole:role       })   }   return (            
                                      

First Name

                 {setName(e.target.value)}} />                 

Company Role

                 {setRole(e.target.value)}} />                                              
        ); } export default App;

Explain details:

  1. Declare two states, a name and a role state to hold the data the user has collected from input fields using the useState hook.
  2. The onChange method of each input field runs a callback that uses state methods to record and save user input via this form.
  3. To send data to the backend server, the onSubmit handler uses Axios.post to send the data passed from the states as an object to the backend API endpoint.

To style the displayed form, add the following code to the App.css file.

* {   padding: 0;   margin: 0;   box-sizing: border-box; } body {   font-family: 'Poppins', sans-serif;   background-color: #8EC1D6; } .logIn-form {   margin: 100px auto;   width: 200px;   height: 250px;   background-color: #fff;   border-radius: 10px; } .logIn-form p {   text-align: center;   font-size: 12px;   font-weight: 600;   color: #B8BFC6;   padding: 10px 10px; } .logIn-form input {   display: block;   width: 80%;   height: 40px;   margin: 10px auto;   border: 1px solid #ccc;   border-radius: 5px;   padding: 0 10px;   font-size: 16px;   color: black; } .logIn-form button {   background-color: #8EC1D6;   color: #fff;   cursor: pointer;   font-size: 15px;   border-radius:7px;   padding: 5px 10px;   border: none; }

Now start the development server to update the changes and navigate to http://localhost:3000 in your browser to see the results.

How to save React form data in Mongo Database Picture 4

Create Express.js backend

An Express backend acts like middleware between the React client and the MongoDB database. From this server, you can define the data schema and establish a connection between the client and the database.

Create a web server and install these two packages:

npm install mongoose cors

Mongoose is an object data prototyping (ODM) library for MongoDB and Note. It provides a diagram-based method to prototype application data and store it in the MongoDB database.

The CORS (Cross-Origin Resource Sharing) package provides a mechanism for the server backend and a client frontend to communicate and transfer data across the API endpoint.

Create a data map

Create a new folder in the root of the server project folder and name it models. In this directory, create a new file: dataSchema.js.

In this case, the schema represents the logical structure of the database. It identifies the documents (records) and fields (attributes) that make up the collection in the database.

Add the following code to dataSchema.js:

const mongoose = require('mongoose'); const ReactFormDataSchema = new mongoose.Schema({     name: {         type: String,         required: true     },     role: {         type: String,         required: true     } }); const User = mongoose.model('User', ReactFormDataSchema); module.exports = User;

This code creates a Mongoose diagram for the User model. The diagram defines the data structure for user data, including the user's name and role. This diagram is then used to create a model for User. This allows the model to store data in a MongoDB collection according to the structure defined in the Schema.

Set up Express Server

Next, open the index.js file in the server project directory and add this code:

const express = require('express'); const mongoose = require('mongoose'); const cors = require('cors'); const app = express(); const User= require('./models/ReactDataSchema') app.use(express.json()); app.use(cors()); mongoose.connect('mongodb://localhost:27017/reactdata', { useNewUrlParser: true }); app.post('/insert', async(req, res) => {     const FirstName = req.body.firstName     const CompanyRole = req.body.companyRole     const formData = new User({         name: FirstName,         role: CompanyRole     })     try {         await formData.save();         res.send("inserted data.")     } catch(err) {         console.log(err)     } }); const port = process.env.PORT || 4000; app.listen(port, () => {     console.log(`Server started on port ${port}`); });

Explain details:

  1. Launch Express, mongoose, and CORS in this server.
  2. The Mongoose package establishes a connection to the MongoDB database using the connect method that takes in the URL domain and an object. The URL is a connection string used to establish a connection with the MongoDB database. This object specifies the configuration. Here it contains a setting to use the latest form of the URL parser.
  3. The web server mainly responds to queries coming from different routes with appropriate handlers. In this case, the server with the POST route receives the data from the React client, saves the selections as variables, and passes them to the imported data model.
  4. This server then uses a try & capture block to store and store the data in the MongoDB database, and log any errors if any.

Finally launch the development server to update the changes and go to the React client in your browser. Enter any data on the form and view the results on the MongoDB database.

4 ★ | 2 Vote

May be interested

  • React mistakes to avoid for successful app developmentReact mistakes to avoid for successful app development
    react is a popular framework that is easy to learn but also easy to make mistakes when programming if you are not careful. here are common react mistakes that you might make during app development.
  • How to manage state in React using JotaiHow to manage state in React using Jotai
    upgrading react app state management with jotai is a simpler alternative to redux, and perfect for small projects. here are detailed instructions.
  • Use the ALTER DATABASE command to migrate DATABASE in SQL ServerUse the ALTER DATABASE command to migrate DATABASE in SQL Server
    technically, you can use the alter database syntax to move any system or user database files that define, initialize, except for the resource database.
  • Test of database security P10Test of database security P10
    database is a data collection organized in a structured way related to each other and stored in a computer. the database is designed and built to allow users to store data, retrieve information or update data. here, please read more about this topic through our quiz below.
  • How to speed up React apps with code splittingHow to speed up React apps with code splitting
    is your react app running too slow or taking too long to load? if that's true, you'll probably resort to code splitting techniques.
  • Transfer form data from Word to ExcelTransfer form data from Word to Excel
    microsoft excel is a powerful spreadsheet database management application. if you are using a word application to collect user data, it is necessary to transfer all of this data to an excel spreadsheet for management. besides, data conversion is a job with multiple records (record) and field (field) data.
  • How to create a Hacker News clone using ReactHow to create a Hacker News clone using React
    are you looking to upgrade your react programming skills? then try to build your own version of hacker news with the help of the guide below.
  • Instructions for editing data in form of PDF fileInstructions for editing data in form of PDF file
    fillable pdf form - forms available in pdf files for users to fill in data, usually they are very useful and convenient compared to printing that text file to paper and manually filling in information.
  • Compare the performance of MongoDB and SQL Server 2008Compare the performance of MongoDB and SQL Server 2008
    in the following article, we will point out the difference in performance of the relatively new database management system, which is mongodb and one of the popular systems like sql server (mysql or oracle). most of the data is given here in the form of charts, so we can easily imagine the advantages and disadvantages of mongodb as well as other database management systems.
  • Rational DA Data Architecture and DB2 9: Build an SQL commandRational DA Data Architecture and DB2 9: Build an SQL command
    are you familiar with database explorer? whether or not, please read the following article to learn about some of the functions and components of this type of data architecture, more specifically about the ability to build sql commands encountered in the database (database ) yours.