I am developing a cart page in Flutter. For deleting a particular item in the cart, I am facing an issue. I want to delete a document inside collection "items" which is inside collection "myOrders"
myOrders => docID => items => docID(to be deleted)
This is the code I tried,
Future deleteData(BuildContext context)
{
final user = Provider.of<Userr?>(context,listen: false);
CollectionReference _collectionRef = FirebaseFirestore.instance.collection('myOrders');
return _collectionRef.doc(user?.uid).collection('items').doc().delete();
}
I need to know why it is not getting deleted and what change I need to do in the code!
2
Answers
Each time you’re calling
.doc()
to create the following reference, without passing anything as an argument:It literally means that you’re always generating a new unique document ID. When you call
delete()
, you’re trying to delete a document that actually doesn’t exist, hence that behavior.If you want to create a reference that points to a particular item (document) inside the
items
sub-collection, then you have to pass the document ID of that item, which already exists in the database, and not generate a brand new one. So to solve this, get the document ID of the item you want to delete and pass it to the.doc()
function like this:You have to pass the id of the document to be deleted.
so modify your code as