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

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

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 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!