Skip to content
Advertisement

Can’t get single item to delete by id from mongoDB in nextjs app

I’m making a todo app in nextjs to practice, and I am having a hard time getting single todos to delete from the database using the deleteOne function.

Here is the call from the front end:

async function deleteTodo(id) {
    await fetch(`/api/todos/${id}`, {
      method: "DELETE",
    });
    setTodosList(todosList.filter((todo) => todo._id !== id));
  }

and here is the handling of the DELETE method:

async function handler(req, res) {
  let client;

  try {
    client = await connectDatabase();
  } catch (error) {
    res
      .status(500)
      .json({ message: error.message || "Error connecting to MongoDB." });

    return;
  }

  if (req.method === "DELETE") {
    const { id } = req.query;

    console.log(id);

    if (!id || id.trim() === "") {
      res
        .status(500)
        .json({ message: "A todo id was not sent with the request." });
      client.close();
      return;
    }

    try {
      let result;
      let allTodos;
      result = await deleteTodo("todos", id);
      allTodos = await getAllTodos("todos");
      res.status(201).json({
        message: `Todo ${id} successfully removed!`,
        todos: allTodos,
      });
    } catch (error) {
      res
        .status(500)
        .json({ message: error.message || "Unable to delete todo." });
    }
  }
  client.close();
}

and the deleteTodo helper function it calls:

export async function deleteTodo(collection, id) {
  const client = await connectDatabase();

  const db = client.db();

  const result = await db.collection(collection).deleteOne({ _id: id });

  return result;
}

I can get it to delete the first item in the array of todos if I pass deleteOne an empty object, but when I try to specify the id by using { _id: id } it does not delete.

Can anyone see what is happening to cause this? Thanks.

Advertisement

Answer

I think your id passed from front-end has string type. Since _id has ObjectId type, you need to convert id string to ObjectId.

Install:

npm i bson

Import in your deleteTodo:

import { ObjectId } from 'bson'; 

and try to change, in deleteTodo

const result = await db.collection(collection).deleteOne({ _id: ObjectId(id) });
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement