通过自动生成的文档ID从Firestore中删除文档 [英] Deleting a document from Firestore via Auto-generated document ID

查看:53
本文介绍了通过自动生成的文档ID从Firestore中删除文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a Property Rental application on Android using Firebase Firestore. Right now, I'm trying to implement a method to delete a specific document (property) within my collection inside Firestore. I figure it is by referencing the auto-generated ID for that particular document, but I simply couldn't get around it.

这是删除功能的工作方式:

This is how the delete feature should work:

  1. 用户从 RecyclerView 中单击一个属性项>
  2. 它显示该属性
  3. 的完整档案
  4. 用户单击右上角的删除按钮,然后从 Firestore数据库

这是我停留在的代码:

@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();
            }
        });
}

推荐答案

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

In order to use the document id that you are looking for, first you need to store it in a variable. When you are adding a document to the database and you are using a call to document() method without passing an argument, a unique id is generated. To get that id, you should use the following code:

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

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

In which postsRef is the CollectionReference object of your Posts collection and yourModelObject is the object of your Post class. I also recommend you store that id, as a property of your Post document.

一旦有了这个ID,就可以像这样使用:

Once you have this id, you can use in your refence like this:

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

这篇关于通过自动生成的文档ID从Firestore中删除文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆