Delete document by content of a field in Firestore (flutter)

Viewed 1144

I have a subcollection 'favourites' under my 'users' collection and I would like to delete any of its documents by checking that the field 'prod_id' is isEqualTo prodId

THis is how I create the subcollection & document when a user taps the favourite button:

      _usersCollectionReference
          .doc(userId)
          .collection('favourites')
          .add({'prod_id': prodId});

Now, I want to be able to delete this document

3 Answers

To delete any document you must know it's ID or have a DocumentReference to it. For that you just need to know the userId and fetch documents where prod_id is equal to the product IDs you want to delete.

FirebaseFirestore.instance
  .collection('users')
  .doc(userId)
  .collection('favourites')
  .where('prod_id', whereIn: [...])
  .get()
  .then((snapshot) {
    // ... 
  });

snapshots is a QuerySnapshot and has a property docs which is an array of QueryDocumentSnapshot. You can loop through that array and delete each document by accessing their reference.

For example, deleting first document in that would be:

snapshot.docs[0].reference.delete()

you can do this very easily and return a result

    let contentArray: any[] = []
  // call the content collection
  const contentRef = db.collection('favourites');
  // snapshot data on get
  const snapshot = await contentRef.get().then((querySnapshot)=>{
// return query snapshot 
      return querySnapshot.docs
      // .map(doc => doc.data());

  })
  // this statement can be joined to the other
  // loop through each snapshot as document
 snapshot.forEach((doc)=>{
   // create new constant as document of each loop
    const newdoc = doc.data()
    // push new constant to content array
    if(newdoc.YOURTHING==='your thing you want to look for'){
    const deleteDocId=newdoc?.id

db.collection('favourites').doc(`${deleteDocId}`).delete().then((result)=>{
              return result
            })
   }

  })
})

You can read about why and how here: https://firebase.google.com/docs/firestore/manage-data/delete-data

You can also do a check on the collection itself with where logic

const snapshot = await contentRef.where('favouritething','==', favoriteId)
  
  .get().then((querySnapshot)=>{
// return query snapshot 
      return querySnapshot.docs
      // .map(doc => doc.data());

  })
Related