如何从Firestore中删除所选文档ID

时间:2018-03-15 19:19:43

标签: java android firebase google-cloud-firestore

如标题所示。我有一个字符串shoppingListId,其中包含当前在RecyclerView documentID中单击的内容,我想知道如何删除此选定的文档ID。

我尝试了以下一个,但由于不兼容的类型,它不起作用:

FirebaseFirestore docRef = FirebaseFirestore.getInstance();
DocumentReference selectedDoc = docRef.collection("products").document(shoppingListId);
selectedDoc.delete();

如何获取Instance to DocumentReference,然后删除所选文档?我想这可能很容易,但我坚持下去。

View of database

@Edit 更改了代码,现在没有任何错误,但它仍然不起作用。

提前致谢, 马切伊

2 个答案:

答案 0 :(得分:2)

FirebaseFirestore docRef = FirebaseFirestore.getInstance();
docRef.collection("products").document(shoppingListId)
     .delete()
     .addOnSuccessListener(new OnSuccessListener<Void>() {
     @Override
     public void onSuccess(Void aVoid) {
           
           // You can write what you want after the deleting process.
     })
     .addOnFailureListener(new OnFailureListener() {
     @Override
     public void onFailure(@NonNull Exception e) {
                                       
     }
     });

答案 1 :(得分:0)

我认为您正在关注 tutorial ,这实际上是由我制作的。

代码中的问题如下:

DocumentReference selectedDoc = docRef.collection("products").document(shoppingListId);

您不能仅使用该行代码删除产品。您的代码不完整。要解决此问题,请使用以下命令更改该行:

DocumentReference productIdRef = rootRef.collection("products").document(shoppingListId)
            .collection("shoppingListProducts").document(productId);
productIdRef.delete().addOnSuccessListener(aVoid -> Snackbar.make(shoppingListViewFragment, "Product deleted!", Snackbar.LENGTH_LONG).show());

如果要删除ShoppingList,首先需要删除其下的所有内容。因此,为了删除特定的购物清单,首先您需要找到shoppingListProducts集合下面的所有文档,然后删除它们,之后您就可以删除shoppingListId文档。

相关问题