Writing my First CRUD app in Express for MongoDB

In the realm of web development, understanding CRUD operations is fundamental to creating robust and dynamic applications. CRUD, an acronym for Create, Read, Update, and Delete, represents the four essential operations that can be performed on data within a system. Whether you're managing user profiles, handling inventory, or processing any form of information, CRUD serves as the backbone for seamless data manipulation.

Create (C): This operation involves the addition of new data to the system. In the context of a web application, it translates to user registration, content creation, or any other form of data entry.

Read (R): Reading is about retrieving and displaying existing data. It's the process of presenting information to users or utilizing it within the application's functionality.

Update (U): As applications evolve, the need to modify existing data arises. The update operation ensures that information can be easily amended, reflecting the dynamic nature of web-based systems.

Delete (D): Deletion, the final operation, involves the removal of unnecessary or outdated data. Efficient data management is crucial for maintaining system performance and integrity.

Here is the simple file in Javascript

//here we are connecting the mongoDB to backend in a simple application
const mongoose = require("mongoose");
const express = require("express");
//please replace username and password
mongoose.connect("mongodb+srv://<username>:<password>@cluster0.qy3a5bn.mongodb.net/")

//We will do all CRUD
/* 
    C: CREATE (Done)
    R: READ (done)
    U: UPDATE (done)
    D: DELETE (done)
*/
const app = express();
app.use(express.json());
const User = mongoose.model('Users', { name: String, email: String, password: String });
//to get the information from http, we need to have something else

//CREATE
app.post('/signup', async function (req, res) {
    const email = req.body.email;
    const password = req.body.password;
    const name = req.body.name;
    //to check if the user not exist already, we need something else
    const existingUser = await User.findOne({ email: email });
    if (existingUser) {
        return res.status(400).send("User already exist");
    }
    const user = new User({
        name: name,
        email: email,
        password: password
    });
    //CREATE
    user.save();
    res.json({
        "msg": "User created successfully"
    })
});


//READ
app.get("/users", async function (req, res) {
    const email = req.headers.email;
    const password = req.headers.password;
    const userExist = await User.findOne({ email: email });
    if(userExist.email === email && userExist.password === password){
        res.status(200).send("User Exist");
    }
    else{
        res.status(400).send("Incorrect Password");
    }
});

//UPDATE
app.put('/users',async function(req, res){
    const email = req.body.email;
    const newName = req.body.name;

    try{
        const updatedUser = await User.findOneAndUpdate({email: email}, {name: newName});
        res.status(200).send({user: updatedUser, msg: "User updated"});
    }
    catch(err){
        res.status(400).send("Error updating the user");
    }
});


// DELETE
app.delete("/users", async function (req, res) {
    const email = req.body.email;

    try {
        const deletedUser = await User.findOneAndDelete({ email: email });

        if (deletedUser) {
            res.status(200).json({ msg: "User deleted successfully" });
        } else {
            res.status(404).json({ msg: "User not found" });
        }
    } catch (err) {
        res.status(400).send("Error deleting user");
    }
});
app.listen(3000, () => { console.log("Running") })

To run this on your local machine, you need to replace the username and password with yours and also install the required dependencies.

That's it for today

Thank you

Signing off

Harsh Chandwani