Search code examples
javascriptgoogle-cloud-firestoreangularfire2

Query delete in Firestore is deleting everything, how to fix it?


I need to remove all docs from a collection, but I should delete only where 'pedido' equals to 'this.pProdutos'. The problem is that, even after querying, it does delete all the docs in the entire collection. I am using this code below right now:

    this.db.collection('produtosPedidos', ref => ref.where('pedido', '==', this.pProdutos)).ref
    .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

  • The problem is caused by the trailing .ref you have at the end of your query here:

    ref.where('pedido', '==', this.pProdutos)).ref
    

    The first part ref.where('pedido', '==', this.pProdutos)) constructs a query, but then calling ref on that query returns a CollectionReference to the entire collection. Remove the trailing .ref and it should work.

    this.db.collection('produtosPedidos', ref => ref.where('pedido', '==', this.pProdutos))
        .get()
        .then(querySnapshot => {
            ...
    

    For this type of operation there is no additional benefit of running it through AngularFire. I recommend simply running it on the bare JavaScript SDK, to reduce the code a bit. Since AngularFire is built on top of the JavaScript SDK, the two interoperate perfectly when you do this.

    In code:

    firebase.firestore().collection('produtosPedidos').where('pedido', '==', this.pProdutos)
        .get()
        .then(querySnapshot => {