check collection existence - Firestore

牧云@^-^@ 提交于 2021-02-08 09:51:28

问题


Example:

I have to make an appointment with the Firestore before proceeding with the event scheduling function.

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.

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.


回答1:


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. Whether or not the underlying document actually exists is available via the exists() method.

If the document does exist you can call getData to get at the contents of it.

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:

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


来源:https://stackoverflow.com/questions/47244134/check-collection-existence-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!