Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

236
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!