When I check the checkbox on my to do list I get an error that say "Model.findByIdAndRemove() no longer accepts a callback".
I am trying to make it so that when an item is checked it is removed from my to do list.
app.post("/delete", function (req, res) {
const checkedItemId = req.body.checkbox;
Item.findByIdAndRemove(checkedItemId, function (err) {
if (!err) {
console.log("Successfully deleted checked item");
res.redirect("/");
}
});
});
This can be easily rolsolved by using async/await
pattern, and findByIdAndDelete
method like so:
app.post("/delete", async (req, res) => { //< Note the use of async and arrow function
try { //< Use a try/catch block for cleaner error handling
const checkedItemId = req.body.checkbox;
const deletedItem = await Item.findByIdAndDelete(checkedItemId); //< Note the use of await keyword
console.log("Successfully deleted checked item:", deletedItem);
res.redirect("/");
} catch(err){
console.log('Error:', err);
//Send error message to front-end
}
});
The findByIdAndDelete
method fires the findOneAndDelete
middleware, which has a useful number of options. See here for the docs.