我正在制作一个应用程序in NextJS练习,我很难使用findByIdAndDelete函数从数据库中删除单个数据.

CastError:对于值"undefined"(type string)强制转换为ObjectId失败 在路径"_id"上,用于模型"约会"

./page.jsx:

import AddAppointment from "./addAppointment";
import DeleteAppointment from "./deleteAppointment";
import UpdateAppointment from "./updateAppointment";

async function getAppointment() {
  const res = await fetch("http://localhost:3000/api/appointment", {
    method: "GET",
    cache: "no-store",
  });
  // const data = await res.json();
  return res.json();
}

async function Appointment() {
  const { appointment } = await getAppointment();

  return (

    <div className="py-10 px-10">
      <div className="py-2">
        <AddAppointment />
      </div>
      <table className="table w-full">
        <thead>
          <tr>
            <th>#</th>
            <th>Nama</th>
            <th>Tanggal</th>
            <th>No Telp.</th>
            <th>Terapis</th>
            <th>Status</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
          {appointment.map((row, i) => (
            <tr key={row._id}>
              <td>{i + 1}</td>
              <td>{row.name}</td>
              <td>{row.date}</td>
              <td>{row.phone}</td>
              <td>{row.terapist}</td>
              <td>{row.statust || "unknown"}</td>
              <td className="flex">
                <UpdateAppointment {...appointment} />
                <DeleteAppointment {...appointment} />
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

export default Appointment;

./deleteAppointment.jsx:

"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";

export default function DeleteAppointment() {
  const [modal, setModal] = useState(false);

  const router = useRouter();

  async function handleDelete({ id }) {
    await fetch(`http://localhost:3000/api/appointment?id=${id}`, {
      method: "DELETE",
    });

    router.refresh();
    setModal(false);
  }

  function handleChange() {
    setModal(!modal);
  }

  return (
    <div>
      <button className="btn btn-error btn-sm" onClick={handleChange}>
        Delete
      </button>

      <input
        type="checkbox"
        checked={modal}
        onChange={handleChange}
        className="modal-toggle"
      />

      <div className="modal">
        <div className="modal-box">
          <h3 className="font-bold text-lg">
            Anda yakin untuk menghapus data ""?
          </h3>

          <div className="modal-action">
            <button type="button" className="btn" onClick={handleChange}>
              Close
            </button>
            <button type="button" onClick={handleDelete} className="btn">
              Delete
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

API route:

import { connectMongoDB } from "@/lib/mongodb";
import Appointment from "@/models/appointment";
import { NextResponse } from "next/server";

export async function DELETE(req) {

  const id = req.nextUrl.searchParams.get("id");
  await connectMongoDB();
  await Appointment.findByIdAndDelete(id);
  return NextResponse.json({ message: "Appointment deleted" }, { status: 200 });
}

Model:

import mongoose, { Schema, models } from "mongoose";

const appointmentSchema = new Schema(
  {
    name: {
      type: String,
      required: true,
    },
    date: {
      type: String,
      required: true,
    },
    phone: {
      type: String,
      required: true,
    },
    terapist: {
      type: String,
      required: true,
    },
    statust: {
      type: String,
      required: true,
    },
  },
  { timestamps: true }
);

const Appointment =
  models.Appointment || mongoose.model("Appointment", appointmentSchema);
export default Appointment;

CastError:对于值"undefined"(type string)强制转换为ObjectId失败 在路径"_id"上,用于模型"约会"

很难弄清楚如何通过id以及id_id之间的区别

推荐答案

onClick函数没有发送参数.id参数是undefined.因此,它发送一个带有undefined id参数的API请求,如下所示:

在客户端,需要使用ObjectID来通过使用findByIdAndDelete()删除文档,但ID参数来自请求为undefined,而不是ObjectID.因此,它无法从DB中找到相关文档,并返回此错误.

因此,这个问题与客户端有关.需要发送正确的ID以删除API参数.因此,需要获取相关行或仅获取id值作为DeleteAppointment组件中的props.

It would be better to send the whole row object into props if you will need to use other fields as well:

// Send related row as prop 
<DeleteAppointment row={row} />

一百零一:

// Send only the related row's ID field as a prop
<DeleteAppointment id={row.id} />

然后在DeleteAppointment组件中获取props作为参数:

export default function DeleteAppointment(props) {
...
}

之后,由于到达props中的相关id,您可以在request id中使用props.idprops.row.id来代替id参数:

async function handleDelete() {
  await fetch(`http://localhost:3000/api/appointment?id=${props.id}`, {
      method: "DELETE",
  });

  router.refresh();
  setModal(false);
}

如果你把整个行对象作为props 发送,那么你可以使用props.row.id:

async function handleDelete() {
  await fetch(`http://localhost:3000/api/appointment?id=${props.row.id}`, {
      method: "DELETE",
  });

  router.refresh();
  setModal(false);
}

霍普,这很清楚很有用

Javascript相关问答推荐

使用JavaScript重命名对象数组中的键

如何最好地从TypScript中的enum获取值

zoom svg以适应圆

在286之后恢复轮询

是什么导致了这种奇怪的水平间距错误(?)当通过JavaScript将列表项元素追加到无序列表时,是否在按钮之间?

在浏览器中触发插入事件时检索编码值的能力

在Java中寻找三次Bezier曲线上的点及其Angular

如何创建返回不带`new`关键字的实例的类

使用getBorbingClientRect()更改绝对元素位置

NG/Express API路由处理程序停止工作

当代码另有说明时,随机放置的圆圈有时会从画布上消失

无法读取未定义的属性(正在读取合并)-react RTK

FireBase云函数-函数外部的ENV变量

当从其他文件创建类实例时,为什么工作线程不工作?

在查看网页时,如何使HTML中的按钮工作方式类似于鼠标上的滚轮或箭头键?

背景动画让网站摇摇欲坠

如何让SVG图标在被点击和访问后改变 colored颜色 ,并在被访问后取消点击时恢复到原来的 colored颜色 ?

调用特定数组索引时,为什么类型脚本不判断未定义

在Press Reaction本机和EXPO av上播放单个文件

如何从Reaction-Redux中来自API调用的数据中筛选值