Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

245
Visualizações
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.

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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) });
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda