简体   繁体   English

检查集合存在-Firestore

[英]check collection existence - Firestore

Example: 例:

I have to make an appointment with the Firestore before proceeding with the event scheduling function. 在继续进行事件调度功能之前,我必须先与Firestore约会。

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

I have a function that performs a new schedule. 我有一个执行新时间表的功能。

According to the example. 根据示例。 I need to check if the Schedules collection exists. 我需要检查Schedules集合是否存在。

If it does not exist I execute the scheduling function. 如果不存在,则执行调度功能。 If I already exist I need to do another procedure. 如果已经存在,则需要执行其他步骤。

I already used this pattern and not right. 我已经使用了这种模式,而不是正确的。

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

I need help finding a way to do this before proceeding with the registration. 在进行注册之前,我需要寻求帮助的方法。

The achieve this just check for nullity: 实现此只需检查无效性即可:

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");
}

The result of this Task is a DocumentSnapshot . Task的结果是DocumentSnapshot Whether or not the underlying document actually exists is available via the exists() method. 基础文档是否实际存在可以通过exist()方法获得。

If the document does exist you can call getData to get at the contents of it. 如果文档确实存在,则可以调用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());
            }
        }
    });

If you want know if the task is empty, please use the following line of code: 如果您想知道task是否为空,请使用以下代码行:

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

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

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