How to delete document from firestore using where clause

JavascriptFirebaseGoogle Cloud-Firestore

Javascript Problem Overview


var jobskill_ref = db.collection('job_skills').where('job_id','==',post.job_id);
jobskill_ref.delete();

Error thrown

> jobskill_ref.delete is not a function

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

//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 - Javascript

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 - Javascript

or try this, but you must have the id beforehand

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

}

Solution 6 - Javascript

And of course, you can use await/async:

exports.delete = functions.https.onRequest(async (req, res) => {
try {
    var jobskill_ref = db.collection('job_skills').where('job_id','==',post.job_id).get();
    jobskill_ref.forEach((doc) => {
      doc.ref.delete();
    });
  } catch (error) {
    return res.json({
      status: 'error', msg: 'Error while deleting', data: error,
    });
  }
});

I have no idea why you have to get() them and loop on them, then delete() them, while you can prepare one query with where to delete in one step like any SQL statement, but Google decided to do it like that. so, for now, this is the only option.

Solution 7 - Javascript

If you're using Cloud Firestore on the Client side, you can use a Unique key generator package/module like uuid to generate an ID. Then you set the ID of the document to the ID generated from uuid and store a reference to the ID on the object you're storing in Firestore.

For example: If you wanted to save a person object to Firestore, first, you'll use uuid to generate an ID for the person, before saving like below.

const uuid = require('uuid') 

const person = { name: "Adebola Adeniran", age: 19}
const id = uuid() //generates a unique random ID of type string
const personObjWithId = {person, id} 

export const sendToFireStore = async (person) => {
  await db.collection("people").doc(id).set(personObjWithId);
};

// To delete, get the ID you've stored with the object and call // the following firestore query

export const deleteFromFireStore = async (id) => {
  await db.collection("people").doc(id).delete();
};

Hope this helps anyone using firestore on the Client side.

Solution 8 - Javascript

You can now do this:

db.collection("cities").doc("DC").delete().then(function() {
    console.log("Document successfully deleted!");
}).catch(function(error) {
    console.error("Error removing document: ", error);
});

Solution 9 - Javascript

The way I resolved this is by giving each document a uniqueID, querying on that field, getting the documentID of the returned document, and using that in the delete. Like so:

(Swift)

func rejectFriendRequest(request: Request) {
    DispatchQueue.global().async {
        self.db.collection("requests")
            .whereField("uniqueID", isEqualTo: request.uniqueID)
            .getDocuments { querySnapshot, error in
                if let e = error {
                    print("There was an error fetching that document: \(e)")
                } else {
                    self.db.collection("requests")
                        .document(querySnapshot!.documents.first!.documentID)
                        .delete() { err in
                            if let e = err {
                                print("There was an error deleting that document: \(e)")
                            } else {
                                print("Document successfully deleted!")
                            }
                        }
                }
            }
    }
}

The code could be cleaned up a bit, but this is the solution I came up with. Hope it can help someone in the future!

Solution 10 - Javascript

The code for Kotlin, including failure listeners (both for the query and for the delete of each document):

fun deleteJobs(jobId: String) {
    db.collection("jobs").whereEqualTo("job_id", jobId).get()
        .addOnSuccessListener { documentSnapshots ->
            for (documentSnapshot in documentSnapshots)
                documentSnapshot.reference.delete().addOnFailureListener { e ->
                    Log.e(TAG, "deleteJobs: failed to delete document ${documentSnapshot.reference.id}", e)
                }
        }.addOnFailureListener { e ->
            Log.e(TAG, "deleteJobs: query failed", e)
        }
}

Solution 11 - Javascript

delete(seccion: string, subseccion: string) 
{
 const deletlist = this.db.collection('seccionesclass', ref => ref.where('seccion', '==', seccion).where('subseccion', '==' , subseccion))
deletlist.get().subscribe(delitems => delitems.forEach( doc=> doc.ref.delete()));
    alert('record erased');
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAmit SinhaView Question on Stackoverflow
Solution 1 - JavascriptFrank van PuffelenView Answer on Stackoverflow
Solution 2 - JavascriptjamstooksView Answer on Stackoverflow
Solution 3 - JavascriptDeepak PoojariView Answer on Stackoverflow
Solution 4 - JavascriptJacob HixonView Answer on Stackoverflow
Solution 5 - JavascriptRa FiView Answer on Stackoverflow
Solution 6 - JavascriptHMagdyView Answer on Stackoverflow
Solution 7 - JavascriptAdebolaView Answer on Stackoverflow
Solution 8 - JavascriptAshish KhareView Answer on Stackoverflow
Solution 9 - JavascriptJason ElwoodView Answer on Stackoverflow
Solution 10 - JavascriptAmir GolanView Answer on Stackoverflow
Solution 11 - JavascriptLuis FigueredoView Answer on Stackoverflow