DEV Community

Cover image for MERN CRUD(Create) - 6
Shubham Tiwari
Shubham Tiwari

Posted on • Edited on

MERN CRUD(Create) - 6

Hello guys today i am going to setup the express server and in my previous blog i have created the form to send data to the backend. Now we are going to create the server and will create a "POST" method.

If you have not seen my previous 5 blogs check them out in sequence and then come back here

Let's get started...

  • As we have created our mongo db connection in our mongo.js file and Schema in our Schema.js file
  • Now we are going to write code in Queries.js file and use it as our Express server

  • Open your Backend folder from your Project folder and open "Queries.js" file and write this code

const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const port = process.env.PORT || 3001;
const mongo = require("./mongo");
const userSchema = require("./Schema/Schema");

const app = express();

app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json());


//post method
app.post("/Register", (req, res) => {
  const connnectToMongo = async () => {
    await mongo().then(async () => {
      try {
        const user = {
          email: req.body.email,
          name: req.body.name,
          number: req.body.number,
        };
         const result = await userSchema(user).save();
         res.send(result);
      }
      catch {
        console.log("error")
      }
      finally {
        console.log("Everything done");
      }
    });
  };
  connnectToMongo();
});


app.listen(port, () => {
  console.log(`running on port ${port}`);
});


Enter fullscreen mode Exit fullscreen mode
  • Here first we have imported the required modules
  • Then Calls the express function "express()" and puts new Express application inside the app variable
  • Then we have used the cors and body-parser which i have discusses already in one of my blogs in this series.
  • Then we have created a post method which is available in express and passed the url as '/Register' and second argument as an arrow function
  • Then we have created a function called "connectToMongo" which is an async function and inside it we have used the "then" method with our "mongo" connection
  • If the connection is successfull with mongo db "then" block will executed , which also contains an async function with try,catch and finally block
  • Inside try block, we will perform our CREATE operation.
  • We will create an object called user and save name,email and number in it and pass the values of our form using "req.body" , here our body parser comes into play which parses the json data coming to the backend from the form.
  • Then create a variable named result and stores the save method of mongo db inside this variable and pass the user object in this save method.
  • Then send the result back to client using res.send(result).

Now open your terminal inside the Backend folder and run this command

npm run dev
Enter fullscreen mode Exit fullscreen mode
  • Dont close this terminal because the server will then be closed.
  • It will start the express server using nodemon js and will refresh automatically when there is some changes in the files.

NOTE - IF YOU DONT HAVE SETUP THE NODEMON THEN CHECK MY PREVIOUS BLOGS WHERE I HAVE SETUP THE NODEMON IN PART 1 OF THIS SERIES NAMED "MERN CRUD SETUP - 1"

Front-end

  • Open the frontend folder again and open the Add.js file and write this code without removing the existing code which we have written in the React Form in our previous Blog.
.
.
import {toastify} from 'react-toaatify
.......
.......
    const [name, setName] = useState("");
    const [email, setEmail] = useState("");
    const [number, setNumber] = useState("");

    const navigation = useNavigate();

  const handleAdd = (e) => {
    e.preventDefault();

    if (!email || !number || !name) {
        return toast("Please fill all the fields");
    }

    const data = {
        name,
        email,
        number
    }
      axios
          .post("http://localhost:3001/Register", data)
                .then((res) => console.log(res))
                .catch((err) => console.log(err));
    toast.success("Saved successfully๐Ÿ˜Ž");
    navigation('/home')
}
Enter fullscreen mode Exit fullscreen mode
  • Now open App.js file and write this line of code App.js
.
.
.
import { ToastContainer } from 'react-toastify'
.
.
.
return (
    <div>
      <ToastContainer />
      <nav className="navbar navbar-expand-lg navbar-dark bg-dark py-4">
.
.
.
.
)
}
Enter fullscreen mode Exit fullscreen mode
  • We are done with CREATE part of our CRUD
  • Open terminal in your front-end folder without closing the terminal of Backend folder , open these terminals separately and in your front-end folder terminal run this command
npm start
Enter fullscreen mode Exit fullscreen mode
  • Now fill the data in your form and click "Add" button the data will be saved in your mongo db database.

Part - 1
https://dev.to/shubhamtiwari909/mern-crud-setup-148a

Part - 2
https://dev.to/shubhamtiwari909/2-mern-mongodb-setup-434g

Part - 3
https://dev.to/shubhamtiwari909/mongodb-connections-using-mongoose-3bl6

Part - 4
https://dev.to/shubhamtiwari909/mern-backend-modules-4-38pk

Part -5
https://dev.to/shubhamtiwari909/mern-react-form-5-53ln

Thats it for this post, i will continue this series in the next blog where i will be creating the "READ" operation of the CRUD in our backend and then display the data in the front-end React Component
THANK YOU FOR READING THIS POST AND IF YOU FIND ANY MISTAKE OR WANTS TO GIVE ANY SUGGESTION , PLEASE MENTION IT IN THE COMMENT SECTION.
^^You can help me by some donation at the link below Thank you๐Ÿ‘‡๐Ÿ‘‡ ^^
โ˜• --> https://www.buymeacoffee.com/waaduheck <--

Also check these posts as well
https://dev.to/shubhamtiwari909/2-mern-mongodb-setup-434g

https://dev.to/shubhamtiwari909/mongodb-connections-using-mongoose-3bl6

https://dev.to/shubhamtiwari909/mern-backend-modules-4-38pk

Top comments (0)