Basic Express methood solution with mongodb and Client & Server site code example

Overview

Express with MongoDB Tutorial (Basic)

React Tutorial

  1. React Inastallation
  2. React Fundamental Concepts
  3. React Advanced concepts

let start Express

Starter template Basic Setup

app.get()

app.post()

app.put()

app.patch()

app.delete()

Basic Setup

Got to top

Embedded on index.jx to Connect.

const express = require("express");
const cors = require("cors");
const { MongoClient, ServerApiVersion, ObjectId } = require("mongodb");
const jwt = require("jsonwebtoken"); // import jwt if use JsonWeb token
require("dotenv").config(); // import env file if use environment variables after install || npm install dotenv --save|| ane Create a .env file in the root of your project:

const port = process.env.PORT || 5000;
const app = express();

// used Middleware
app.use(cors());
app.use(express.json());

// Connact With MongoDb Database
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.krxly.mongodb.net/?retryWrites=true&w=majority`;

const client = new MongoClient(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  serverApi: ServerApiVersion.v1,
});

// Create a async fucntion to all others activity
async function run() {
  try {
    await client.connect();

    // Create Database to store Data
    const testCollection = client.db("testDatabaseName").collection("testData");


  } finally {
    // await client.close();
  }
}

// Call the fuction you decleare abobe
run().catch(console.dir);

// Root Api to cheack activity
app.get("/", (req, res) => {
  res.send("Hello From NR Computers!");
});

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

Get Methood

Got to top

Get/Access all data from mongodb database

Server Site Code

app.get("/service", async (req, res) => {
      const result = await testCollection.find().toArray();
      res.send(result);
    });

Client site code

useEffect(() => {
      fetch("http://localhost:5000/service")
        .then((res) => res.json())
        .then((data) => console.log(data));
    }, []);

Get/Access Spacific data from mongodb database with id/email

Server Site Code

app.get("/service/:id", async (req, res) => {
const id = req.params.id;
const result = await testCollection.find({ _id: ObjectId(id) }).toArray();
res.send(result);
});

Client site code

useEffect(() => {
fetch(`http://localhost:5000/service/${id}`)
.then((res) => res.json())
.then((data) => console.log(data));
}, []);

Get/Access Spacific data from mongodb database with multiple query

Server Site Code

app.get("/service", async (req, res) => {
const query = req.body;
const result = await testCollection.find(query).toArray();
res.send(result);
});

Client site code

    const query = {
      email: "[email protected]",
      name: "set name",
      time: "set time",
    };
    useEffect(() => {
      fetch("http://localhost:5000/service", {
        method: "GET",
        body: JSON.stringify(query), // send any of query by which you find data
      })
        .then((res) => res.json())
        .then((data) => console.log(data));
    }, []);

Get/Access Limited data from mongodb database after find with query

Server Site Code

    app.get("/service", async (req, res) => {
      const query = {};
      const findData = testCollection.find(query);
      const result = await findData.skip(5).limit(3).toArray(); // you can also set skip & limit range dynamicly.
      res.send(result);
    });

Client site code

 useEffect(() => {
      fetch("http://localhost:5000/service")
        .then((res) => res.json())
        .then((data) => console.log(data));
    }, []);

Post Methood

Got to top

Post data without cheack on mongodb database

Server Site Code

app.post("/service", async (req, res) => {
const service = req.body;
const result = await testCollection.insertOne(service);
res.send(result);
});

Client site code

    const newData = {
      // stroe new Data in Object here
      name: "",
      price: "",
    };
    fetch("http://localhost:5000/service", {
      method: "POST",
      headers: {
        "content-type": "application/json",
      },
      body: JSON.stringify(newData),
    })
      .then((res) => res.json())
      .then((result) => {
        const allData = [...previusData, newData];
        console.log(newReview);
      });

Post data With cheack in mongodb database. Batter to use Put Methood for this task

Server Site Code

    app.post("/service/:email", async (req, res) => {
      const service = req.body.service;
      const query = req.body.newQuery;
      query.email = email;
      const exist = testCollection.findOne(query);
      if (exist) {
        res.send({ result: "success" });
      } else {
        const result = await testCollection.insertOne(service);
        res.send(result);
      }
    });

Client Site Code

    const service = {
      name: "",
      price: "",
    };
    const newQuery = {
      name: "",
      time: "",
    };
    fetch("http://localhost:5000/service", {
      method: "POST",
      headers: {
        "content-type": "application/json",
      },
      body: JSON.stringify({ service, newQuery }),
    })
      .then((res) => res.json())
      .then((result) => {
        const allData = [...previusData, newData];
        console.log(newReview);
      });

Put Methood

Got to top

Update & insert Data on database by id/email/otherQuery

Server site Code

    app.put("/service/:id", async (req, res) => {
      const id = req.params.id;
      const service = req.body;

      const result = await testCollection.updateOne(
        { _id: ObjectId(id) }, // Find Data by query many time query type is "_id: id" Cheack on database
        {
          $set: service, // Set updated Data
        },
        { upsert: true } // define work
      );
      res.send({ result });
    });

Client Site Code

const updatedData = {
name: "",
role: "",
};

    fetch(`http://localhost:5000/service/${id}`, {
      method: "PUT",
      headers: {
        "content-type": "application/json",
      },
      body: JSON.stringify(updatedData),
    })
      .then((res) => res.json())
      .then((data) => {
        alert("item Updated successfully!!!");
      });

Patch Methood

Got to top

update Data by id/email/othersQueary

Server site code

app.patch("/service/:id", async (req, res) => {
const id = req.params.id;
const service = req.body;
const result = await testCollection.updateOne(
{ _id: id }, // sometime _id:ObjectId(id)
{
$set: service,
}
);
res.send(result);
});

Client site code

const updatedData = {
      name: "",
      role: "",
    };

    fetch(`http://localhost:5000/service/${id}`, {
      method: "patch",
      headers: {
        "content-type": "application/json",
      },
      body: JSON.stringify(updatedData),
    })
      .then((res) => res.json())
      .then((data) => {
        alert("item Updated successfully!!!");
      });

Delete Methood

Got to top

Delete Data form mongodb Database by id

Server site code

app.delete("/service/:id", async (req, res) => {
const id = req.params.id;
const result = await testCollection.deleteOne({ _id: ObjectId(id) });
res.send(result);
});

Client Site Code

    fetch(`http://localhost:5000/service/${_id}`, {
      method: "DELETE",
    })
      .then((res) => res.json())
      .then((data) => {});
You might also like...

A type speed checking website which lets you check your typing speed and shows the real-tme leaderboards with mongodb as DB and express as backend

This is a Next.js project bootstrapped with create-next-app. Getting Started First, run the development server: npm run dev # or yarn dev Open http://

Mar 27, 2022

implements user authentication and session management using Express.js, MongoDB, and secure cookies

Auth-Flow This project is a simple user authentication system that uses Express.js and MongoDB to store user data. The system allows users to sign up

Mar 17, 2023

BASIC is a web application contains basic applications related to studies, love, health, weather, productivity. This project aim to simply the user's life in anyway.

BASIC is a web application contains basic applications related to studies, love, health, weather, productivity. This project aim to simply the user's life in anyway.

BASIC is a web application contains basic applications related to studies, love, health, weather, productivity. This project aim to simply the user's life in anyway. Supported by all operating system, need an internet connection for working properly.

Dec 19, 2021

This will create a REST API using Express JS and MongoDB removing the hassle of creating everything from scratch.

rest-api-init Fastest way to create REST API with Node.js, Express.js & MongoDB. Prerequisites Node.js needs to be installed. MongoDB Compass needs to

Dec 3, 2022

📄 UI clone from vercel old site (Using basic tools)

📄 UI clone from vercel old site (Using basic tools)

vercel old site A portfolio site, made using the latest technologies. In the construction of the site using Sass. Quality: 1) Benchmark test using a s

Mar 1, 2022

Web client with support for secret chats. Made as a temporary solution

Web client with support for secret chats. Made as a temporary solution

Arcanugram – Unofficial Telegram Web App with support for secret chats ⚠️ Made as a temporary solution for use on devices that do not have any clients

Sep 19, 2022

This repository contains a basic example on how to set up and run test automation jobs with CircleCI and report results to Testmo.

CircleCI test automation example This repository contains a basic example on how to set up and run test automation jobs with CircleCI and report resul

Dec 23, 2021

A remote nodejs Cache Server, for you to have your perfect MAP Cache Saved and useable remotely. Easy Server and Client Creations, fast, stores the Cache before stopping and restores it again!

A remote nodejs Cache Server, for you to have your perfect MAP Cache Saved and useable remotely. Easy Server and Client Creations, fast, stores the Cache before stopping and restores it again!

remote-map-cache A remote nodejs Cache Server, for you to have your perfect MAP Cache Saved and useable remotely. Easy Server and Client Creations, fa

Oct 31, 2022

Online Inventory Control System for an apparel manufacturing company "CASANOVA" (Pvt) Ltd. Technology stack: Node.js, Express.js, MongoDB Atlas, React.js (MERN Stack).

Project Name - Online Inventory Control System for an apparel manufacturing company "CASANOVA". The project was given a "A" grade. Group Leader - IT20

Dec 26, 2021
Owner
Md. Nazmul Islam
Full-Stack Web developer
Md. Nazmul Islam
A "Basic-to-Lisp" compiler. But Basic is not real Basic, and Lisp is not real Lisp.

Basic2Lisp A "Basic-to-Lisp" compiler. But Basic is not real Basic, and Lisp is not real Lisp. Syntax Print-Sth Put some-value to standard output. PRI

Hana Yabuki 5 Jul 10, 2022
Example auto-generated OpenAPI client library and an accompanying example Angular app.

To utilize this demo Head into petstore_frontend\petes_pets Run npm install Go to frontend_client_lib\out Run npm install Head back into petstore_fron

Alan Gross 1 Jan 21, 2022
Learn Basic of Node Express Server and Git & Github by creating Pull Request in this repository.

hacktoberfest-express-server-2022 Learn Basic of Node Express Server and Git & Github by creating Pull Request in this repository. Special Note For Ev

NetScape-Web 3 Oct 6, 2022
Here I will add daily one problem with solution basic to advance level and try to add multiple solutions of a single problem.

#100-code-days ?? I am adding daily 1 JavaScript solution here ?? and you can fork the repo for add your solution for any specific probelm ⌛️ Day 01:

Amir Sohel 4 Jan 22, 2022
A developer directory built on Next.js and MongoDB Atlas, deployed on Vercel with the Vercel + MongoDB integration.

MongoDB Starter – Developer Directory A developer directory built on Next.js and MongoDB Atlas, deployed on Vercel with the Vercel + MongoDB integrati

Vercel 246 Dec 20, 2022
Mongo Strict is a TypeScript based smart MongoDB ORM, It makes the usage of MongoDB safer, easier and faster with a better performance...

mongo-strict mongo-strict is compatible with mongo >= 5 Mongo Strict is a TypeScript-based smart MongoDB ORM, It makes the usage of MongoDB safer, eas

Mohamed Kamel 4 Sep 22, 2022
A simple example repo that demonstrates the dynamic ephemeral storage solution for AWS Lambda outlined in the corresponding Storyboard Dev Blog post.

AWS Lambda Dynamic Ephemeral Storage Example A simple example repo that demonstrates the dynamic ephemeral storage solution for AWS Lambda outlined in

Storyboard.fm 3 Jun 14, 2022
This project will be a basic website that allows users to add/remove books from a list. The main objective is to understand how to use JavaScript objects and arrays and dynamically modify the DOM and add basic events.

Awesome-books Awesome Books This project will be a basic website that allows users to add/remove books from a list. This project is part of the Microv

Aleksandra Ujvari 10 Oct 3, 2022
A Nextjs e-commerce site with mongodb

A Nextjs starter template on Gitpod This is a Learn Next.js template configured for ephemeral development environments on Gitpod. Next Steps Click the

Padmashree Jha 7 Oct 22, 2022
Basic website that allows users to add/remove books from a list. Achieved using JavaScript objects and arrays, dynamically modifying the DOM and adding basic events.

Awesome Books Basic website that allows users to add/remove books from a list. Achieved using JavaScript objects and arrays, dynamically modifying the

Didier Peran Ganthier 6 Dec 20, 2022