mongodb 为什么我不能通过findByIdAndRemove()将id发送到后台并删除项目?

rekjcdws  于 2023-04-05  发布在  Go
关注(0)|答案(1)|浏览(123)

我想从mongodb中删除项目。我把所有项目都提取到一个页面上。然后我使用map()把项目放到卡片上。一个项目在卡片中,包含编辑btn和删除btn,删除btn有id(item.id)。我抓住这个id并发送到后端,并通过这个id删除项目,但我得到了未定义的id。

const deletehandler = async (id) => {
  console.log(typeof id, id) // I am getting id = string
  
  try {
     await axios.delete('/api/delete', id)
  } catch (error) {
    console.log(error)
  } 
}

return ( ...
{
 getData.map(item => {
          return (
            <>
              <div key={item.name} className='card'>
                <span className='ps-2'>{item.name}</span>
               
                  <RiDeleteBin5Line style={{cursor: 'pointer'}}
                      onClick={() => deletehandler(item._id)}/>
                
              </div>
}

API/delete文件夹:

import { getSession } from 'next-auth/react';
import db from "@/utils/db";
import User from "@/modules/User";

const handler = async (req, res) => {
  console.log(req.body) // ===> here I am getting undefine 

  await db.connect();
  await User.findByIdAndRemove(id)
  await db.disconnect(); 
  res.status(200).json({ message: 'success '})
};

export default handler
k0pti3hp

k0pti3hp1#

与axios.post()和axios.put()不同,axios.delete()的第二个参数是Axios选项,而不是请求正文。要发送带有DELETE请求的请求正文,您应该使用data选项。

const deletehandler = async (id) => {
  console.log(typeof id, id) // I am getting id = string
  
  try {
     await axios.delete('/api/delete', { data: {id} });
  } catch (error) {
    console.log(error)
  } 
}

https://masteringjs.io/tutorials/axios/delete

相关问题