skip to Main Content

0

I have a MERN app, used Fetch API. I want to delete specific data upon clicking.

I have also given endpoint for delete.

Whenever i am clicking on delete its showing ‘cannot delete.’

and Status is 404: Not Found

Here is my front end code please help me with this

What I have tried:


import {useState,useEffect} from 'react';
import './App.css';

function App() {

  const userArr = [
    {}
  ]

 const [form, setForm] = useState(userArr);
 const [users,setUsers] = useState([]);
 
 const [sid,setId] = useState("");
 const [fname, setFName] = useState("");
 const [pass,setPass] = useState("");




 const handleName = (e) =>{
    setFName(e.target.value);
  
   
 }

 const handlePass = (e) =>{
  setPass(e.target.value);
  console.log("pass is -->"+pass)
 }

 const handleForm = (e) =>{
  setId(Math.random()+1);
  setForm({
    ...form,
    userid: sid,
    username:fname,
    password:pass
  })
 }

 const removeElm = async (userid) =>{
  
  fetch(`http://localhost:9090/demo/users/${userid}`, {
    method: "DELETE",
    headers: {
     'content-Type': 'application/json',
    },
  })
    .then(response => response.text())
    .then((err) => console.log(err))
    .then(() => {
      setUsers(values => {
        return values.filter(item => item.userid !== userid)
      })
})

 }

 const handleSubmit = async (e) =>{
  e.preventDefault();
  const response = await fetch("http://localhost:9090/demo",{
    method:'POST',
    body:JSON.stringify(form),
    headers:{
      'Content-Type':'application/json'
    }
  })

  const data = await response.json();
  console.log(form);
  console.log(response);
  console.log(data);
 }

 const getUsers = async () =>{
  const response = await fetch("http://localhost:9090/demo",{
    method:'GET',
  })

  const data = await response.json();
  setUsers(data);
 }
    
 useEffect(()=>{
  getUsers();
 },[])

  return (
    <div className="App">
     <div>
      <form onSubmit={handleSubmit}>
      <label htmlFor="username">Username</label>
       <input type="text" name='username' onChange={handleName} />
       <label htmlFor="password">Password</label>
       <input type="text" name='password' onChange={handlePass} />
       <button onClick={handleForm}>Submit</button>
      </form>
     </div>
     <ul>
     {users.map(obj=><li key={obj.userid}> <span>Username:{obj.username}</span>, <span>Password:{obj.password}</span>  <button onClick={() => removeElm(obj.userid)}>Remove</button> </li>
   )}
     </ul>
    </div>
  );
}

export default App;

Backend

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');


// mongo db
main().catch(err => console.log(err));

async function main() {
  await mongoose.connect('mongodb://127.0.0.1:27017/demo');
  console.log('db connected');
}

// schema
const userSchema = new mongoose.Schema({
      userid: Number,
    username: String,
    password: String
  });

// model- class from schema
const UserModel= mongoose.model("User",userSchema);
console.log(UserModel) // to check if the Model has been created successfully or not


const server = express();
// middleware
server.use(cors());
server.use(bodyParser.json());

// API
//CRUD - Create
server.post('/demo',async (req,res)=>{
    let user = new UserModel();
    user.userid  = req.body.userid;
    user.username = req.body.username;
    user.password = req.body.password;
    // save function
    const savedDoc = await user.save();
    console.log(savedDoc);
    res.json(savedDoc);
})

//CRUD - Read
server.get('/demo',async (req,res)=>{
  const docs =  await UserModel.find({});
  console.log("All Docs=>"+docs);
  res.json(docs);
})

//CRUD - Delete
server.delete("/demo/userid", async (req, res) => {
  try{
    const idToDelete = req.params.userid;
    const deletedItem =await UserModel.findByIdAndDelete({"_id":mongoose.Types.ObjectId(idToDelete)});
    return res.status(204).send({message:"Deleted Successfully!"});
    }catch(error){
      throw error;}
  });



server.listen(9090,()=>{
    console.log(`Server is running on port 9090`);
})

Please help me with the above problem

2

Answers


  1. It looks like you are trying to access an non-existing route with

    fetch(`http://localhost:9090/demo/users/${userid}`, {
    method: "DELETE",
    headers: {
     'content-Type': 'application/json',
    },
    

    })

    when your delete defined route in backend is:

    server.delete("/demo/userid", ...)
    

    You probably should change your backend route like as shown below to match your frontend call:

    server.delete("/demo/users/:userid",...)
    

    Don’t forget the ":" before userid to make it a parameter.

    EDIT

    Regarding the following error you are getting now

     const deletedItem =await UserModel.findByIdAndDelete({"_id":mongoose.Types.ObjectId(idToDelete)}); ^ TypeError: Class constructor ObjectId cannot be invoked without 'new'
    

    I’m not an expert in MongoDB and Mongoose but as I understand it, you are mixing the auto-created unique _id of type ObjectId of you UserModel with the manually created userid of type number.

    Also, the method mongoose.Types.ObjectId() is a class constructor and should be use with "new" (hence your new error). It is used to create a unique ID in your schema as explained in the documentation: https://mongoosejs.com/docs/schematypes.html

    As I see things, you’ve got two solutions. Either you keep using your userid (according you are sure it’s unique) and you update your delete function like this:

    await UserModel.deleteMany({ userid: userid})
    

    Either you recover the real _id auto-created by Mongo and simply adapt your method as followed

    await UserModel.findByIdAndDelete(id)
    

    Or the long version:

    await UserModel.findOneAndDelete({ _id: id })
    

    Hope this can help

    Login or Signup to reply.
  2. Add ‘new’ keyword before mongoose.Types.ObjectId(idToDelete)

    Try Using This:

    new mongoose.Types.ObjectId(idToDelete)

    Server Code:

      server.delete("/demo/users/:id", async (req, res) => {
        try{
          const idToDelete = req.params.id;
          console.log("-->Its Running");
          const deletedDoc =await UserModel.findByIdAndDelete({"_id": new mongoose.Types.ObjectId(idToDelete)});
          console.log("Its Running2"); 
          return res.status(204).send('Deleted');
            }catch(err){
            new Error(err);
          };
      });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search