Issue with delete command:
Unanswered
Polar bear posted this in #help-forum
Polar bearOP
Attatched is my jsx file and my delete api (stored as app/api/deleteService/[serviceId]/route.js). In my delete method my service id is always undefined so I am unable to delete the service. Does anyone know how to fix this? Please note my id is in mongodb as _id.
Api:
// /pages/api/deleteService/[serviceId].js
import { connectMongoDB } from "@/lib/mongodb";
import Service from "@/models/services"; // Ensure this model correctly points to your services collection
export async function DELETE(req, res) {
await connectMongoDB();
// Logging the query to debug
console.log("Received query parameters:", req.query);
const serviceId = req.query.serviceId;
if (!serviceId) {
res.status(400).json({ message: 'Service ID is required' });
return;
}
try {
const deleteResult = await Service.deleteOne({ _id: serviceId });
if (deleteResult.deletedCount === 0) {
res.status(404).json({ message: 'No service found with the provided ID' });
return;
}
res.status(200).json({ message: 'Service deleted successfully' });
} catch (error) {
console.error('Error deleting service:', error);
res.status(500).json({ message: 'Failed to delete the service' });
}
}
Api:
// /pages/api/deleteService/[serviceId].js
import { connectMongoDB } from "@/lib/mongodb";
import Service from "@/models/services"; // Ensure this model correctly points to your services collection
export async function DELETE(req, res) {
await connectMongoDB();
// Logging the query to debug
console.log("Received query parameters:", req.query);
const serviceId = req.query.serviceId;
if (!serviceId) {
res.status(400).json({ message: 'Service ID is required' });
return;
}
try {
const deleteResult = await Service.deleteOne({ _id: serviceId });
if (deleteResult.deletedCount === 0) {
res.status(404).json({ message: 'No service found with the provided ID' });
return;
}
res.status(200).json({ message: 'Service deleted successfully' });
} catch (error) {
console.error('Error deleting service:', error);
res.status(500).json({ message: 'Failed to delete the service' });
}
}
33 Replies
So your code should be like this i think:
import { connectMongoDB } from "@/lib/mongodb";
import Service from "@/models/services";
import { NextRequest, NextResponse } from "next/server";
export async function DELETE(req: NextRequest) {
await connectMongoDB();
// Logging the query to debug
console.log("Received query parameters:", req.nextUrl.searchParams);
const serviceId = req.nextUrl.searchParams.get('serviceId');
if (!serviceId) {
return new NextResponse(JSON.stringify({ message: 'Service ID is required' }), { status: 400 });
}
try {
const deleteResult = await Service.deleteOne({ _id: serviceId });
if (deleteResult.deletedCount === 0) {
return new NextResponse(JSON.stringify({ message: 'No service found with the provided ID' }), { status: 404 });
}
return new NextResponse(JSON.stringify({ message: 'Service deleted successfully' }), { status: 200 });
} catch (error) {
console.error('Error deleting service:', error);
return new NextResponse(JSON.stringify({ message: 'Failed to delete the service' }), { status: 500 });
}
}this errors for me
oh wait its bc i am using js not tsx my bad
1 sec
i am now getting this error
this is how the page looks for reference
the service names are listed and the user can select one to delete
but the code errors when we select one and press delete
the console log shows the service id
Sloth bear
Ahm try:
import { connectMongoDB } from "@/lib/mongodb";
import Service from "@/models/services";
import { NextApiRequest, NextApiResponse } from "next";
export async function DELETE(req: NextApiRequest, res: NextApiResponse) {
await connectMongoDB();
// Logging the query to debug
console.log("Received query parameters:", req.query);
const serviceId = req.query.serviceId;
if (!serviceId) {
return res.status(400).json({ message: 'Service ID is required' });
}
try {
const deleteResult = await Service.deleteOne({ _id: serviceId });
if (deleteResult.deletedCount === 0) {
return res.status(404).json({ message: 'No service found with the provided ID' });
}
return res.status(200).json({ message: 'Service deleted successfully' });
} catch (error) {
console.error('Error deleting service:', error);
return res.status(500).json({ message: 'Failed to delete the service' });
}
}like this?
import { connectMongoDB } from "@/lib/mongodb";
import Service from "@/models/services";
import { NextApiRequest, NextApiResponse } from "next";
export async function DELETE(NextApiRequest, NextApiResponse) {
await connectMongoDB();
// Logging the query to debug
console.log("Received query parameters:", req.query);
const serviceId = req.query.serviceId;
if (!serviceId) {
return res.status(400).json({ message: 'Service ID is required' });
}
try {
const deleteResult = await Service.deleteOne({ _id: serviceId });
if (deleteResult.deletedCount === 0) {
return res.status(404).json({ message: 'No service found with the provided ID' });
}
return res.status(200).json({ message: 'Service deleted successfully' });
} catch (error) {
console.error('Error deleting service:', error);
return res.status(500).json({ message: 'Failed to delete the service' });
}
}(mb if this seems like a dumb question lol im new to this 😭 )
Sloth bear
Oh so you are using regular js didn't notice that
you can do it like that:
import { connectMongoDB } from "@/lib/mongodb";
import Service from "@/models/services";
export default async function deleteService(req, res) {
console.log("Connecting to MongoDB...");
await connectMongoDB();
console.log("Request Query Parameters:", req.query);
const { serviceId } = req.query;
console.log("Extracted Service ID:", serviceId);
if (!serviceId) {
console.log("No Service ID provided, sending 400 response.");
return res.status(400).json({ message: 'Service ID is required' });
}
try {
console.log(`Attempting to delete service with ID: ${serviceId}`);
const deleteResult = await Service.deleteOne({ _id: serviceId });
console.log("Deletion Result:", deleteResult);
if (deleteResult.deletedCount === 0) {
console.log("No service found with the provided ID, sending 404 response.");
return res.status(404).json({ message: 'No service found with the provided ID' });
}
console.log("Service deleted successfully, sending 200 response.");
return res.status(200).json({ message: 'Service deleted successfully' });
} catch (error) {
console.error('Error deleting service:', error);
return res.status(500).json({ message: 'Failed to delete the service' });
}
}@Polar bear (mb if this seems like a dumb question lol im new to this 😭 )
Sloth bear
Dw i been struggling too, not very familiar with it
@Sloth bear Dw i been struggling too, not very familiar with it
Polar bearOP
the console log is showing the correct value
so would the issue be in the api file?
Polar bearOP
My res.query is undefined
but my res
when console logged
shows the correct id in the url
any suggestions?
Polar bearOP
ive mangaged to get it to work ty for the help <33
@Polar bear ive mangaged to get it to work ty for the help <33
Sloth bear
Happy to hear that
What did you do?
Also don't forget to mark it as solution