Learn how to delete a document from a collection in Firebase version 9 Cloud Firestore using the deleteDoc() method.
- Delete A Document from a collection → you’re here
- Delete A Field from a document
Here is the sample document from the cities collection in Cloud Firestore Database that I want to delete.
First, import Firestore Database and de-structure the three methods we need:
- getFirestore()
- doc()
- deleteDoc()
import { getFirestore, doc, deleteDoc } from "firebase/firestore";
Initialize Firestore Database and assign it to the constant db.
const db = getFirestore();
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);
})
When you delete the last document of a collection, the collection itself will be deleted.
Top comments (1)
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)