[英]Firebase: How to delete collection within a collection?
I am developing a cart page in Flutter. For deleting a particular item in the cart, I am facing an issue.我正在 Flutter 开发一个购物车页面。为了删除购物车中的特定商品,我遇到了一个问题。 I want to delete a document inside collection "items" which is inside collection "myOrders"
我想删除集合“items”中的文档,它位于集合“myOrders”中
myOrders => docID => items => docID(to be deleted) myOrders => docID => items => docID(待删除)
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!我需要知道为什么它没有被删除以及我需要在代码中做哪些更改!
You have to pass the id of the document to be deleted.您必须传递要删除的文档的 ID。 so modify your code as
所以修改你的代码
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('document_id_to_be_deleted').delete();
}
Each time you're calling .doc()
to create the following reference, without passing anything as an argument:每次调用
.doc()
来创建以下引用时,不传递任何参数:
_collectionRef.doc(user?.uid).collection('items').doc()
// 👆
It literally means that you're always generating a new unique document ID.它的字面意思是您总是在生成一个新的唯一文档 ID。 When you call
delete()
, you're trying to delete a document that actually doesn't exist, hence that behavior.当您调用
delete()
时,您正在尝试删除实际上不存在的文档,因此会出现这种行为。
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.如果要创建指向
items
子集合中特定项目(文档)的引用,则必须传递数据库中已存在的该项目的文档 ID,而不是生成全新的文档 ID。 So to solve this, get the document ID of the item you want to delete and pass it to the .doc()
function like this:因此,要解决此问题,请获取要删除的项目的文档 ID,并将其传递给
.doc()
function,如下所示:
_collectionRef.doc(user?.uid).collection('items').doc('itemDocId')
// 👆
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.