Delete document by content of a field in Firestore (flutter)
Solution 1
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());
})
Solution 2
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()
William Chidube
Updated on December 31, 2022Comments
-
William Chidube over 1 year
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
-
William Chidube almost 3 yearsPerhaps I wasn't clear enough. Passing the userId isn't sufficient to know which specific favourite document to delete. To know this, I need to check one of the fields of the favourite document which is where I store the productId and see that it is equal to the prodId received. In other words I (think) have to query the favourite collection/document for the value of a particular field and if that value is equal to the value I received from the onTap, I can then delete that document.
-
chris burd almost 3 yearsI understand what you want to do give me a second and I will update the answer above.
-
William Chidube almost 3 yearsOkay thanks. I'll try this out immediately and update you asap.
-
chris burd almost 3 yearsthis won't be exact William no ones answer will be but it will be very close to what you want - the idea is to loop through each document on a collection and if it matched your variable either let var or const - then it will delete that item. Just be careful if this is a very large collection it can be expensive. you can further refine this by using ref and where on the collection query if you wanted too as well.
-
William Chidube almost 3 yearsThis is understood, Chris
-
Dharmaraj almost 3 yearsThis answer uses Javascript but should be good to clarify the same.