简体   繁体   中英

MongoDB / Axios / React.js : Cannot read property 'id' of undefined"

I try to delete an item, i searched a solution on google, i compared with other posts, i tried with "findByOneAndRemove" and PostMan too but didn't works..

I don't understand because i see the id in request with console.log

Can you help me ?

Server.js :

app.delete("/argonautes/:id", async (res, req, next) => {
    try {
        await db.Argonaute.findOneAndDelete({_id : req.params.id})
        return success(res, "Argonaute deleted !" )
    } catch (err) {
        next({ status: 400, message : "Failed to delete an Argonaute" + err})
    }
});

APP.js

const deleteArgonaute = async (id) => {

    axios.delete(`/argonautes/${id}`)
      .then((res) => {
        console.log(res);
      })
      .catch((err) => {
        console.error(err);
      })
  } 

component.js

<section className="w-full flex flex-col h-64 p-2 flex-wrap relative">
                {argonautes.map( ({_id, name}) => (
                            <div className="shadow-lg p-2 mx-auto rounded my-2 animate-scale relative" key={_id}>
                                {name}
                                <FaMinusCircle className="absolute cursor-pointer top-0 right-0 text-gray-500" onClick={() => deleteArgonaute(_id)}/>
                            </div>
                ))}
            </section>

Thanks in advance :)

Your app.delete code looks right, I did tested and it worked. What can occur sometimes (and happened to me once) is that you may receive a extra invisible character on your id params string.

You can test it by hard pasting an _id on your deleteArgonaute(),if it works it means you need to check what you are really receiving.

Worked for me adding a id.trim().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM