检查集合存在 - Firestore

时间:2017-11-12 00:04:39

标签: android firebase google-cloud-firestore

示例:

在继续进行事件安排功能之前,我必须预约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());
                }
            }
        });

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

1 个答案:

答案 0 :(得分:3)

实现此目的只是检查无效:

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();
相关问题