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

159
Visualizações
How to dynamically delete MongoDB entry using API route

I would just like to simply delete a record from a dynamically displayed list. I've tried every permutation of the backend code and ai just can't get it to work.

The backend is called like this:

async function deletePost() {
    setLoading(true)
    try {
        await axios.delete(`/api/delete/${id}`)
        alert("Post deleted")
    }
    catch (err) {
        // notify user that something went wrong
        console.log(err)
    }
    finally {
        setLoading(false)
    }

    setLoading(false)
}

And /api/delete/${id} looks like this:

import { connectToDatabase } from "util/mongodb"
export default async (req, res) => {
    const { id } = req.query;
    console.log(id)
    try {
        const { db } = await connectToDatabase()
        await db.collection("users").deleteOne({'_id': `ObjectId("${id}")`})
        res.sendStatus(200).send({ done: true })
    }
    catch (error) {
        return res.json({ error })
    }
 }

The console log shows the correct post id, the alert in the 'try' frontend code displays, but the dam post just wont delete. Can anyone offer any advice please? I have tried ".deleteOne({'_id': id})" but that does nothing either.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

I believe you are searching for a string, instead of the ObjectId, so no documents match.

You can fix it by converting to ObjectId and then using the value converted, .deleteOne.

var ObjectId = require('mongodb').ObjectId; 
const { id } = req.query;     
const convertedObjectId = new ObjectId(id);
db.collection("users").deleteOne({_id: convertedObjectId })

Actual example from documentation:

try {
   db.orders.deleteOne( { "_id" : ObjectId("563237a41a4d68582c2509da") } );
} catch (e) {
   print(e);
}

Reference: MongoDB Documentation - Delete One.

over 4 years ago · Santiago Trujillo Relatório

0

Fixed problem:

app.delete("/cars/:id", async (req, res) => {
    const carsId = req.params.id;
    const query = { _id: ObjectId(carsId) };
    const result = await carCollection.deleteOne(query);
    res.send(result);
});

over 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