Performance: Deleting documents
This affects server response time and client perceived speed when removing data from a database via an Express API.
Jump into concepts and practice - no test required
app.delete('/item/:id', async (req, res) => { try { const id = req.params.id; await db.collection('items').deleteOne({ _id: new ObjectId(id) }); res.send('Deleted'); } catch { res.status(500).send('Error'); } });
app.delete('/item/:id', (req, res) => { const id = req.params.id; db.collection('items').findOneAndDelete({ _id: new ObjectId(id) }, (err, result) => { if (err) return res.status(500).send('Error'); res.send('Deleted'); }); });
| Pattern | Server Blocking | Event Loop Impact | Response Time | Verdict |
|---|---|---|---|---|
| Callback with blocking DB call | High | Blocks event loop | Slower | [X] Bad |
| Async/await non-blocking DB call | Low | Non-blocking | Faster | [OK] Good |
deleteOne() method do in Express when working with a database?deleteOne() purposedeleteOne() method removes only one document that matches the given filter.deleteMany() deletes multiple documents, and find() only retrieves data without deleting.deleteOne() = deletes one document [OK]findByIdAndDelete() which deletes a document by its ID.Model.findByIdAndDelete(id, callback); matches the official Mongoose syntax.findByIdAndDelete to delete by ID [OK]Model.deleteMany({ status: 'inactive' })
.then(result => console.log(result.deletedCount))
.catch(err => console.error(err));deleteMany() returns an object with deletedCount indicating how many documents were deleted.result.deletedCount, so it outputs the number of deleted documents matching the filter.deleteMany() returns deletedCount [OK]Model.deleteOne({ _id: id }, (err, doc) => {
if (err) console.log(err);
else console.log(doc);
});doc representsresult or similar to reflect it contains deletion info like deletedCount, not the document.doc should be result to access deletion info. -> Option Dactive is false, but only if the user confirms. Which Express code snippet correctly handles this with error checking?if(confirm) check to ensure deletion only happens after user confirmation.deleteMany to delete all matching documents, logs the count, and catches errors properly.