Head of the Node.js
const express = require('express');
const cors = require('cors');
require('dotenv').config()
const { MongoClient, ServerApiVersion, ObjectId } = 
require('mongodb');
const app = express();
const port = process.env.PORT || 5000;
// middleware
app.use(cors())
app.use(express.json())
Get method Backend:
 app.get('/users', async (req, res) => {
            const cursor = usersCollection.find();
            const result = await cursor.toArray();
            res.send(result)
        })
Delete Method Front-end:
 fetch('https://example.com/delete-item/' + id, {
            method: 'DELETE',
        })
            .then(res => res.text()) // or res.json()
            .then(res => console.log(res))
Delete method Back-end:
 app.delete('/delete/:id', async (req, res) => {
    const id = req.params.id;
    const query = { _id: new ObjectId(id) };
    const result = await usersCollection.deleteOne(query);
    res.send(result)
   })
Post method Front-end
fetch('http://localhost:5000/users', {
            method: 'POST',
            headers: {
                'content-type': 'application/json'
            },
            body: JSON.stringify(newUser)
        })
            .then(res => res.json())
            .then(data => {
                console.log(data);
                form.reset();
            })
Post method Back-end:
app.post('/users', async (req, res) => {
            const user = req.body;
            const result = await usersCollection.insertOne(user);
            res.send(result);
        });
Update method Front-end:
        fetch(`http://localhost:5000/users/${loadedUser?._id}`, {
            method: 'PUT',
            headers: {
                'content-type': 'application/json',
            },
            body: JSON.stringify(updatedUser)
        })
            .then(res => res.json())
            .then(data => {
                console.log(data);
            })
Update Method Back-end:
 app.put('/users/:id', async (req, res) => {
   const id = req.params.id;
   const requestedUser = req.body;
   const filter = { _id: new ObjectId(id) };
   const options = { upsert: true };
   const updatedUser = {
      $set: {
              name: requestedUser?.name,
              email: requestedUser?.email,
             }
           }
   const result = await usersCollection.updateOn
                  (filter, updatedUser, options);
   res.send(result)
        })
Post a Comment