繁体   English   中英

检查集合存在-Firestore

[英]check collection existence - 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());
                }
            }
        });

在进行注册之前,我需要寻求帮助的方法。

实现此只需检查无效性即可:

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 基础文档是否实际存在可以通过exist()方法获得。

如果文档确实存在,则可以调用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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM