How to delete document from firestore using where clause

Solution 1:

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

Solution 2:

I use batched writes for this. For example:

var jobskill_ref = db.collection('job_skills').where('job_id','==',post.job_id);
let batch = firestore.batch();

jobskill_ref
  .get()
  .then(snapshot => {
    snapshot.docs.forEach(doc => {
      batch.delete(doc.ref);
    });
    return batch.commit();
  })

ES6 async/await:

const jobskills = await store
  .collection('job_skills')
  .where('job_id', '==', post.job_id)
  .get();

const batch = store.batch();

jobskills.forEach(doc => {
  batch.delete(doc.ref);
});

await batch.commit();

Solution 3:

//The following code will find and delete the document from firestore

const doc = await this.noteRef.where('userId', '==', userId).get();
doc.forEach(element => {
    element.ref.delete();
    console.log(`deleted: ${element.id}`);
});

Solution 4:

the key part of Frank's answer that fixed my issues was the .ref in doc.ref.delete()

I originally only had doc.delete() which gave a "not a function" error. now my code looks like this and works perfectly:

let fs = firebase.firestore();
let collectionRef = fs.collection(<your collection here>);

collectionRef.where("name", "==", name)
.get()
.then(querySnapshot => {
  querySnapshot.forEach((doc) => {
    doc.ref.delete().then(() => {
      console.log("Document successfully deleted!");
    }).catch(function(error) {
      console.error("Error removing document: ", error);
    });
  });
})
.catch(function(error) {
  console.log("Error getting documents: ", error);
});

Solution 5:

or try this, but you must have the id beforehand

export const deleteDocument = (id) => {
return (dispatch) => {
    firebase.firestore()
    .collection("contracts")
    .doc(id)
    .delete()
}

}