无法在nextjs应用程序中通过id从mongoDB中删除

问题描述 投票:0回答:1

0

我正在 nextjs 中制作一个应用程序来练习,但我很难使用 findByIdAndDelete 函数从数据库中删除单个数据。

CastError:对于模型“约会”的路径“_id”处的值“未定义”(类型字符串),转换为 ObjectId 失败

./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;

./删除约会.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 路线

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 });
}

型号

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:对于模型“约会”的路径“_id”处的值“未定义”(类型字符串),转换为 ObjectId 失败

很难弄清楚如何传递 id 以及 id 和 _id 之间的区别

javascript reactjs mongodb rest next.js
1个回答
0
投票

看来错误不在您的数据库ORM内,而是在您传递ID的位置,您可以检查

id
中的值是什么吗,错误表明您传递的
id
未定义。请检查该值并确保其正确传递。

© www.soinside.com 2019 - 2024. All rights reserved.