Complete the code to delete a document by ID using Express and Mongoose.
app.delete('/items/:id', async (req, res) => { try { await Item.[1](req.params.id); res.send('Deleted successfully'); } catch (error) { res.status(500).send(error.message); } });
The findByIdAndDelete method deletes a document by its ID in Mongoose.
Complete the code to send a 404 status if the document to delete is not found.
app.delete('/users/:id', async (req, res) => { const deletedUser = await User.findByIdAndDelete(req.params.id); if (![1]) { return res.status(404).send('User not found'); } res.send('User deleted'); });
req.params.id instead of the deleted document.We check if deletedUser is null or undefined to know if the user was found and deleted.
Fix the error in the code to delete a document using Express and Mongoose.
app.delete('/posts/:id', async (req, res) => { try { const result = await Post.[1]({ _id: req.params.id }); if (result.deletedCount === 0) { return res.status(404).send('Post not found'); } res.send('Post deleted'); } catch (err) { res.status(500).send(err.message); } });
remove which is deprecated.findByIdAndDelete which returns the deleted document, not a result with deletedCount.The deleteOne method deletes a single document matching the filter and returns a result with deletedCount.
Fill both blanks to delete multiple documents matching a condition and send the count of deleted documents.
app.delete('/tasks/completed', async (req, res) => { const result = await Task.[1]({ completed: true }); res.send(`Deleted [2] completed tasks`); });
find which only retrieves documents.count instead of deletedCount.deleteMany deletes all documents matching the filter. The deletedCount property shows how many were deleted.
Fill all three blanks to delete a document by ID, handle errors, and send appropriate responses.
app.delete('/comments/:id', async (req, res) => { try { const deleted = await Comment.[1](req.params.id); if (![2]) { return res.status(404).send('Comment not found'); } res.[3]('Comment deleted'); } catch (error) { res.status(500).send(error.message); } });
deleteOne with ID directly (needs filter object).res.sendStatus instead of res.send for success message.Use findByIdAndDelete to delete by ID. Check if deleted is null to handle not found. Use send to send the response.