Reputation: 43
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
});
}
}
Upvotes: 4
Views: 3420
Reputation: 523
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
.
Upvotes: 4