首页 文章

通过自动生成的文档ID从Firestore中删除文档

提问于
浏览
0

我正在尝试使用Firebase Firestore在Android上创建Property Rental应用程序 . 现在,我正在尝试实现一种方法来删除Firestore中我的集合中的特定文档(属性) . 我认为它是通过引用该特定文档的自动生成的ID,但我根本无法解决它 .

这是删除功能应该如何工作:

这是我的代码,我被困在:

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch(item.getItemId()){
        // The delete button
        case R.id.action_delete_btn:
            // Do this when user clicks on delete button
            Toast.makeText(PropertyProfile.this, "You tried to delete this property", Toast.LENGTH_LONG).show();

            deleteItem(item.getOrder());
            return super.onOptionsItemSelected(item);

        default:
            return false;
    }
}

// Here's my problem
private void deleteItem(int index) {
    firebaseFirestore.collection("Posts")
        .document("[DOCUMENT ID RIGHT HERE!]")
        .delete()
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Toast.makeText(PropertyProfile.this, "You successfully deleted this property", Toast.LENGTH_LONG).show();
            }
        });
}

1 回答

  • 2

    要使用您要查找的文档ID,首先需要将其存储在变量中 . 将文档添加到数据库并且在不传递参数的情况下使用 document() 方法调用时,将生成唯一的ID . 要获取该ID,您应该使用以下代码:

    String documentId = postsRef.document().getId();
    yourRef.document(documentId).set(yourModelObject);
    

    其中 postsRefPosts 集合的 CollectionReference 对象, yourModelObjectPost 类的对象 . 我还建议您将该ID存储为Post文档的属性 .

    一旦你有了这个id,就可以在你的refence中使用这样的:

    firebaseFirestore
        .collection("Posts")
        .document(documentId)
        .delete().addOnSuccessListener(/* ... */);
    

相关问题