DEV Community

Cover image for Firebase V9 Firestore DELETE Document Using deleteDoc()
Raja Tamil
Raja Tamil

Posted on Originally published at softauthor.com

Firebase V9 Firestore DELETE Document Using deleteDoc()

Learn how to delete a document from a collection in Firebase version 9 Cloud Firestore using the deleteDoc() method.

Here is the sample document from the cities collection in Cloud Firestore Database that I want to delete.

alt text

First, import Firestore Database and de-structure the three methods we need:

  • getFirestore()
  • doc()
  • deleteDoc()
import { getFirestore, doc, deleteDoc } from "firebase/firestore";
Enter fullscreen mode Exit fullscreen mode

Initialize Firestore Database and assign it to the constant db.

const db = getFirestore();
Enter fullscreen mode Exit fullscreen mode

The deleteDoc() method takes one method as an argument to perform the delete operation which is

  • doc()

The doc() method takes three arguments which are:

  • database → db
  • collection name → cities
  • document ID → yftq9RGp4jWNSyBZ1D6L (ID of a document – see screenshot above)

Call the doc() method and pass references of database, collection name and ID of a document that we want to delete.

Assign it to a constant called docRef.

Let’s make a deleteDoc() query to perform deleting a document from a cities collection in Cloud Firestore.

import {getFirestore, doc, deleteDoc} from "firebase/firestore";

const db = getFirestore();

const docRef = doc(db, "cities", "yftq9RGp4jWNSyBZ1D6L");

deleteDoc(docRef)
.then(() => {
    console.log("Entire Document has been deleted successfully.")
})
.catch(error => {
    console.log(error);
})

Enter fullscreen mode Exit fullscreen mode

When you delete the last document of a collection, the collection itself will be deleted.

alt text

Top comments (1)

Collapse
 
guruprasathv profile image
Guruprasath

Ok i have a doubt here, Adding a document requires just addDoc(collectionRef, data)
but deleting requires again to point the data why not it designed like following: deleteDoc(collectionRef, docId)