Home > Net >  How delete documents from a Firestore collection with a 'where' clause in Web v9
How delete documents from a Firestore collection with a 'where' clause in Web v9

Time:10-30

I'm struggling to complete the following code:

const myCollection = collection(db, 'myCollection');
const mycollectionQuery = query(myCollection, where("field1", "==", "xyz"));
myCollectionSnapshot.forEach((doc) => {
     deleteDoc(?);
});

Advice on what to supply inside the deleteDoc call would be much appreciated. I was pretty confident it would be doc.id, but this returns a "Cannot use 'in' operator to search for '_delegate' in undefined" error message

CodePudding user response:

In V9, the deleteDoc() method takes a DocumentReference, as documented here.

As you can see from the documentation of your forEach(), the doc variable will be a QueryDocumentSnapshot, that is a specialization of DocumentSnapshot. It means that, if you want to retrieve the DocumentReference for your doc, you just need to reference to it via doc.ref.

In other words, to delete the document you'll need to do this:

myCollectionSnapshot.forEach((doc) => {
     deleteDoc(doc.ref);
});

CodePudding user response:

This is how you delete a document from cloud firestore:

deleteDoc(doc(db, "reference"))

So, the complete code is:

const myCollection = collection(db, 'myCollection');
const mycollectionQuery = query(myCollection, where("field1", "==", "xyz"));
myCollectionSnapshot.forEach((doc) => {
     deleteDoc(doc(db, doc.ref));
});
  • Related