Consider this Express route that deletes a user by ID from a MongoDB collection using Mongoose. What will the client receive if the user is successfully deleted?
app.delete('/users/:id', async (req, res) => { try { const result = await User.findByIdAndDelete(req.params.id); if (!result) { return res.status(404).send('User not found'); } res.send('User deleted'); } catch (error) { res.status(500).send('Server error'); } });
Look at the condition checking if result is null or not.
The code checks if result is null, which means no user was found. Only if a user was found and deleted does it send 'User deleted'.
Choose the correct syntax to delete a document by ID using Mongoose in an Express route.
app.delete('/items/:id', async (req, res) => { // delete code here });
Check the official Mongoose method names for deleting by ID.
findByIdAndRemove is the correct Mongoose method to delete a document by its ID. deleteById does not exist. deleteOne works but requires a filter object. remove is deprecated.
Look at this Express route code. It always sends 'User deleted' even if the user ID does not exist in the database. What is the bug?
app.delete('/users/:id', async (req, res) => { try { await User.findByIdAndDelete(req.params.id); res.send('User deleted'); } catch (error) { res.status(500).send('Server error'); } });
Think about what findByIdAndDelete returns when no document is found.
findByIdAndDelete returns null if no document matches. The code does not check this and always sends 'User deleted'.
deletedCount after this delete operation?Given this Mongoose delete operation, what will deletedCount be if the document with the given ID exists?
const result = await User.deleteOne({_id: req.params.id});
const deletedCount = result.deletedCount;Check the Mongoose deleteOne result object properties.
If a document is deleted, deletedCount is 1. If none deleted, it is 0.
When deleting documents in Express routes, which pattern is best to catch and handle errors globally?
Think about how Express error middleware works with next().
Calling next(error) inside catch blocks passes errors to centralized error middleware, which is best practice for maintainability.