Home > other >  delete collection firebase in v9
delete collection firebase in v9

Time:11-09

can some one explain how can i delete collection in firebase/firestore using v9 using reactjs

firestore()
  .collection('rate')
   .get()
  .then((querySnapshot) => {
  querySnapshot.forEach((doc) => {
    doc.ref.delete();
  });

this code i am using in v8 i need same thing in v9

 const q = query(collection(db, `${udata.id}`));
    const querySnapshot = await getDocs(q);
    querySnapshot.forEach((doc) => {
      // doc.data() is never undefined for query doc snapshots
      console.log(doc.data());
      
    });

already try this but this code only read data this can't allow me to delete so can some one tell me how to do it

CodePudding user response:

You can use deleteDoc(), as documented here.

deleteDoc() takes a document reference, so you'll need to pass the reference from inside the forEach. In the forEach you're receiving a QueryDocumentSnapshot, so you just need to add a

deleteDoc(doc.ref);

CodePudding user response:

There's a top-level function deleteDoc() to delete documents in using Modular SDK:

import { collection, query, getDocs, deleteDoc } from 'firebase/firestore';

const q = query(collection(db, `${udata.id}`));
const querySnapshot = await getDocs(q);
    
const deleteOps = [];

querySnapshot.forEach((doc) => {
  deleteOps.push(deleteDoc(doc.ref));      
});

Promise.all(deleteOps).then(() => console.log('documents deleted'))
  • Related