Home > OS >  Where to pass an objectId as a property when deleting an entry?
Where to pass an objectId as a property when deleting an entry?

Time:10-29

I have an app that allows users to add notes, and I'm trying to add a delete functionality to the page. My route:

router.route('/:id').delete((req, res) => {
Note.findByIdAndDelete(req.params.id)
    .then(() => res.json('Exercise deleted!'))
    .catch(err => res.status(err).json('Error '   err))
})

works when I test it in Postman, but I haven't managed to get the ObjectId from the database. It throws an error: Invalid status code: CastError: Cast to ObjectId failed for value "undefined" (type string) at path "_id" for model "Note" .

This is my Note schema:

const noteSchema = new Schema({
category: {type: String, required: false},
title: {type : String, required: true},
content: {type: String, required: true},
noteID: { type: mongoose.SchemaTypes.ObjectId, required: true, index: true }
}, {
timestamps: true,
})

This is my Note component:

import React from "react";
function Note(props) {
function handleClick() {
    props.onDelete(props.id);
  }
return (
<div className="note">
      <h1>{props.title}</h1>
      <p>{props.content}</p>
      <button onClick={handleClick}>
        Delete
</button>
      <p>{props.category}</p>
</div>
  );
  }
export default Note

my App component:

function App() {
const [notes, setNotes] = useState([]);
useEffect(() => {
fetch('http://localhost:5000/notes')
    .then(res => res.json())
    .then(json => setNotes(json))
  }, [])
function deleteNote(id) {
    axios.delete('http://localhost:5000/notes/' id)
      .then(response => { console.log(response.data)});
  }

{notes.map((noteItem, index) => {
return (
          <Note
key={index}
//id={index}
title={noteItem.title}
content={noteItem.content}
category={noteItem.category}
onDelete={deleteNote}
/>
        );

I'm not sure where to pass the id from the database, I tried passing it as a parameter in App.js (deleteNote(note.id)) or some variation of it, but it doesn't work. Could someone please tell me which step I'm missing to get the ObjectId? I also tried passigng noteItem._id when mapping notes to the Note component, but that deletes all notes at once. I tried these solutions as well: https://stackoverflow.com/questions/71544895/how-do-i-solve-casterror-cast-to-objectid-failed-for-value-undefined-type-s and https://stackoverflow.com/questions/63253129/successfully-delete-an-object-in-mongodb-using-findbyidanddelete-but-returns-an but I still get errors. Thanks in advance!

CodePudding user response:

Two issues. CastError: Cast to ObjectId failed for value "undefined" (type string) at path "_id" for model "Note"

First of all, the id you are getting is undefined. This may cause problems, check if your client is sending the id properly, either via logging or debugging. If you pass in a correct string, Mongoose should automatically cast it for you.

If it didn't work, try using mongoose.Types.ObjectId(req.params.id)

CodePudding user response:

I finally figured it out! I also put everything in the Note component to avoid any confusion, and through that I discovered what the problem was my endpoint was incorrect: instead of <button onClick={handleClick}> I had to turn it into an arrow function to call handleClick correctly and pass noteItem._id. I also got rid of the noteID property in the schema.

This is the Note component now:

import React, {useState,useEffect} from "react";
import axios from "axios";

function Note(props) {
  const [notes, setNotes] = useState([])

  useEffect(() => {
    fetch('http://localhost:5000/notes')
    .then(res => res.json())
  .then(json => {console.log(json)
    setNotes(json)})
  }, [])

  function deleteNote(id) {
    axios.delete(`http://localhost:5000/notes/${id}`)
    .then(() => { console.log("Note successfully deleted")});
  }

return (
  <div>
  {notes.map((noteItem, index) => {
    return (
        <div className="note">
       <h1>{noteItem.title}</h1>
       <p>{noteItem.content}</p>
       <button onClick={() => {deleteNote(noteItem._id)}}>
         Delete
       </button>
       <p>{noteItem.category}</p>
     </div>
  
    );
  })}
  </div>
)
  }
  
  export default Note
  • Related