How to Delete a Document in Firestore: Simple Guide
To delete a document in Firestore, use the
delete() method on a document reference obtained via doc(). This removes the document and its data from the database immediately.Syntax
The basic syntax to delete a document in Firestore involves getting a reference to the document and then calling delete() on it.
doc(db, 'collectionName', 'documentId'): Gets the reference to the document.deleteDoc(): Deletes the document at that reference.
javascript
import { getFirestore, doc, deleteDoc } from 'firebase/firestore'; const db = getFirestore(); const docRef = doc(db, 'collectionName', 'documentId'); await deleteDoc(docRef);
Example
This example shows how to delete a document with ID 'user123' from the 'users' collection in Firestore.
javascript
import { initializeApp } from 'firebase/app'; import { getFirestore, doc, deleteDoc } from 'firebase/firestore'; const firebaseConfig = { // your config here }; const app = initializeApp(firebaseConfig); const db = getFirestore(app); async function deleteUser() { const userDoc = doc(db, 'users', 'user123'); try { await deleteDoc(userDoc); console.log('Document deleted successfully'); } catch (error) { console.error('Error deleting document:', error); } } deleteUser();
Output
Document deleted successfully
Common Pitfalls
Common mistakes when deleting Firestore documents include:
- Using
deleteDoc()on a collection reference instead of a document reference. - Not awaiting the
deleteDoc()promise, which can cause unexpected behavior. - Trying to delete a document that does not exist, which does not throw an error but does nothing.
javascript
import { collection, doc, deleteDoc } from 'firebase/firestore'; /* Wrong: Trying to delete a collection (this will cause an error) */ const collectionRef = collection(db, 'users'); // await deleteDoc(collectionRef); // ❌ This is invalid /* Right: Delete a specific document */ const docRef = doc(db, 'users', 'user123'); await deleteDoc(docRef); // ✅ Correct usage
Quick Reference
| Action | Code Snippet | Description |
|---|---|---|
| Get Document Reference | doc(db, 'collection', 'docId') | Points to the document to delete |
| Delete Document | await deleteDoc(docRef) | Deletes the document at the reference |
| Handle Errors | try { await deleteDoc(docRef); } catch (e) { } | Catch errors during deletion |
Key Takeaways
Use a document reference with deleteDoc() to remove a Firestore document.
Always await the deleteDoc() promise to ensure deletion completes.
Deleting a non-existent document does not cause an error.
Do not try to delete collections directly; delete documents only.
Handle errors with try-catch to manage deletion failures gracefully.