0
0
GcpHow-ToBeginner · 3 min read

How to Delete a Document in Firestore: Simple Guide

To delete a document in Firestore, use the delete() method on a document reference. 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 calling the delete() method on it.

  • documentReference: Points to the specific document you want to delete.
  • delete(): Method that removes the document from Firestore.
javascript
const docRef = firestore.collection('collectionName').doc('documentId');
docRef.delete();
💻

Example

This example shows how to delete a document named user123 from the users collection using Node.js Firestore SDK.

javascript
const { Firestore } = require('@google-cloud/firestore');

const firestore = new Firestore();

async function deleteUser() {
  const docRef = firestore.collection('users').doc('user123');
  await docRef.delete();
  console.log('Document user123 deleted successfully');
}

deleteUser().catch(console.error);
Output
Document user123 deleted successfully
⚠️

Common Pitfalls

Common mistakes when deleting Firestore documents include:

  • Trying to delete a document without a valid reference causes errors.
  • Not awaiting the delete() promise can lead to unexpected behavior.
  • Deleting a document that does not exist does not throw an error but does nothing.

Always check your document path and handle asynchronous calls properly.

javascript
/* Wrong way: Missing await, may cause unhandled promise */
const docRef = firestore.collection('users').doc('user123');
docRef.delete();

/* Right way: Await the delete operation */
await docRef.delete();
📊

Quick Reference

ActionCode SnippetNotes
Get Document Referencefirestore.collection('name').doc('id')Points to the document to delete
Delete DocumentdocRef.delete()Removes the document asynchronously
Await Deletionawait docRef.delete()Ensures deletion completes before next step
Handle Non-ExistenceNo error if doc missingSafe to call delete even if doc doesn't exist

Key Takeaways

Use the delete() method on a document reference to remove a Firestore document.
Always await the delete() call to ensure the operation completes.
Deleting a non-existent document does not cause errors.
Verify the document path is correct before deleting.
Handle asynchronous calls properly to avoid unexpected results.