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

138
Visualizações
deleteMany showing 0 deleted but actually deleting the documents

this controller is deleting all the todos of particular user but in response it is showing {n: 0, deletedCount: 0, ok: 1}, does anyone knows the solution of it?

exports.deleteAll = async (req, res) => {

    const { id } = req.user

    console.log('id', id);

    try {
        // const deleteAllTodos = await TodoModel.findByIdAndDelete(id)

        const deleteAllTodos = await TodoModel.deleteMany({ createdBy: id}, function (err) { 

        console.log('err', err) })

        res.send({ success: true, message: "All todos deleted successfully", deleteAllTodos })

    } catch (error) {

        console.log('Error:', error.message);

        res.status(500).json({
            message: "Internal server error",
            success: false,
            error: error.message
        });

    }
}
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

From mongoose Query guides

Don't mix using callbacks and promises with queries, or you may end up with duplicate operations. That's because passing a callback to a query function immediately executes the query, and calling then() executes the query again.

So what you did there was calling deleteMany twice, first using the callback and then using the async/await. The second attempt will try to delete nothing because the first attempt has already deleted them.

You could try using either one:

...
const deleteAllTodos = await TodoModel.deleteMany({ createdBy: id }).exec();
res.send({ 
    success: true, 
    message: "All todos deleted successfully", 
    deleteAllTodos 
})

Don't worry about error handling using callback as you have already done it with the try/catch block which will catch if any error happened on deleteMany.

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