【问题标题】:check collection existence - Firestore检查集合是否存在 - Firestore
【发布时间】:2017-11-12 00:04:38
【问题描述】:

例子:

在继续使用事件调度功能之前,我必须与 Firestore 预约。

Example in the database:
- Companie1 (Document)
--- name
--- phone
--- Schedules (Collection)
-----Event 1
-----Event 2

我有一个执行新计划的函数。

根据示例。 我需要检查 Schedules 集合是否存在。

如果它不存在,我执行调度功能。如果我已经存在,我需要做另一个过程。

这个模式我已经用过了,不对。

db.collection("Companies").document(IDCOMPANIE1)
        .get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (DocumentSnapshot document : task.getResult()) {

                    }
                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });

在继续注册之前,我需要帮助找到一种方法。

【问题讨论】:

    标签: android firebase google-cloud-firestore


    【解决方案1】:

    实现这个只是检查无效性:

    DocumentSnapshot document = task.getResult();
    if (document != null) {
        Log.d(TAG, "DocumentSnapshot data: " + task.getResult().getData());
        //Do the registration
    } else {
        Log.d(TAG, "No such document");
    }
    

    Task 的结果是DocumentSnapshot。通过exists() 方法可以获得底层文档是否实际存在。

    如果文档确实存在,您可以调用 getData 来获取它的内容。

    db.collection("Companies").document(IDCOMPANIE1)
        .get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (DocumentSnapshot document : task.getResult()) {
                        if(document.exists()) {
                            //Do something
                        } else {
                            //Do something else
                        }
    
                    }
                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });
    

    如果您想知道task 是否为空,请使用以下代码行:

    boolean isEmpty = task.getResult().isEmpty();
    

    【讨论】:

    • 我需要检查集合 Schedules 是否存在。所以我只检查它是否有任何数据? @AlexMamo
    • 是的,只要看看 ti 是否为空。如果不是,则表示包含信息。
    • 是的,但您将始终拥有这些信息。除了收集时间表。这个可能会也可能不会。我只需要检查它是否存在。 @AlexMamo
    • 即使使用 getData 我也无法检查该集合是否存在。 @AlexMamo
    • 您不需要使用 getData()。请查看我的更新答案。
    猜你喜欢
    • 2021-12-22
    • 2021-09-15
    • 2019-04-19
    • 2019-01-21
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    • 2018-06-11
    • 1970-01-01
    相关资源
    最近更新 更多