How to Delete Document from Firestore Using Where Clause

How to delete document from firestore using where clause

You can only delete a document once you have a DocumentReference to it. To get that you must first execute the query, then loop over the QuerySnapshot and finally delete each DocumentSnapshot based on its ref.

var jobskill_query = db.collection('job_skills').where('job_id','==',post.job_id);
jobskill_query.get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
doc.ref.delete();
});
});

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

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);
});

How to delete a document when multiple conditions are matched, firestore firebase

You can only write (and thus delete) a document in Firestore if you know the complete, exact path to that document. Firestore does not support the equivalent of SQL's DELETE FROM facilityOwners WHERE ... queries.

This means that you will first have to get() the results of the query, loop through them, and delete each document individually, or in batches. Something like:

let query = db.collection('facilityOwners').where('facilityId', '==', facilityId).where('ownerId', '==', ownerId);
query.get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
doc.ref.delete();
});
});

Also see:

  • Cloud Firestore Swift: How to delete a query of documents
  • How to delete document from firestore using where clause


Related Topics



Leave a reply



Submit