#Issue with delete command:

34 messages · Page 1 of 1 (latest)

finite night
#

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

}

oblique spireBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

dusk compass
#

So your code should be like this i think:

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 });
    }
}```
finite night
#

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

dusk compass
#

Ahm try:

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' });
    }
}```
finite night
#

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 😭 )

dusk compass
#

Oh so you are using regular js didn't notice that

#

you can do it like that:

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' });
    }
}
dusk compass
finite night
#

so would the issue be in the api file?

#

My res.query is undefined

#

but my res

#

when console logged

#

shows the correct id in the url

#

any suggestions?

#

ive mangaged to get it to work ty for the help <33

dusk compass
#

What did you do?