Learn how to delete a document in Firestore with this step-by-step guide covering Firebase setup, function coding, and security rule configuration.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Step 1: Set Up Firebase
Ensure that you have set up a Firebase project and added Firestore to your application. Here is a simple guide on how to achieve that:
Step 2: Set Up Your Development Environment
Make sure you've included the Firebase SDK in your project. You need to initialize Firebase and Firestore in your development environment. Here's how you can do this for a JavaScript project using npm:
// Install Firebase using npm
npm install firebase
// Import Firebase in your project
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER\_ID",
appId: "YOUR_APP_ID"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
// Initialize Firestore
const db = getFirestore(app);
Step 3: Write the Function to Delete a Document
You need a function that can delete a document from Firestore. Here's an example:
import { doc, deleteDoc } from 'firebase/firestore';
// Function to delete a document
async function deleteDocument(collectionName, documentId) {
try {
// Get a reference to the document
const docRef = doc(db, collectionName, documentId);
// Delete the document
await deleteDoc(docRef);
console.log(`Document with ID ${documentId} has been deleted successfully.`);
} catch (error) {
console.error("Error deleting document: ", error);
}
}
Step 4: Use the Delete Function
Now, call the deleteDocument function with the collection name and the document ID you wish to delete:
// Example usage of deleteDocument function
deleteDocument('collectionName', 'documentId');
Step 5: Security Rules
Make sure your Firestore security rules allow for deletion if your app requires authentication. Here's a sample rule configured for public access (suitable for development only):
service cloud.firestore {
match /databases/{database}/documents {
match /{document=\*\*} {
allow read, write: if request.auth != null;
}
}
}
Replace request.auth != null with your specific condition if you need more secure access settings.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.