How to check if the field exists in firestore?

Viewed 16618

I am checking whether the Boolean field called attending exists, however I am not sure how to do that.

Is there a function such as .child().exists() or something similar that I could use?

firebaseFirestore.collection("Events")
    .document(ID)
    .collection("Users")
    .get()
    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if(task.isSuccessful()) {
                for(QueryDocumentSnapshot document: task.getResult()){
                    attending = document.getBoolean("attending");
                }
            }
        }
    });
5 Answers

What you're doing now is correct - you have to read the document and examine the snapshot to see if the field exists. There is no shorter way to do this.

You can do the following:

  if(task.isSuccessful()){
    for(QueryDocumentSnapshot document: task.getResult()){
       if (document.exists()) {
          if(document.getBoolean("attending") != null){
             Log.d(TAG, "attending field exists");
          }
        }
      }
  }

From the docs:

public boolean exists ()

Returns true if the document existed in this snapshot.

Here is how you can achieve it or you may have resolved already, this for any one searches for solution.

As per the documentation:

CollectionReference citiesRef = db.collection("cities");

Query query = citiesRef.whereNotEqualTo("capital", false);

This query returns every city document where the capital field exists with a value other than false or null. This includes city documents where the capital field value equals true or any non-boolean value besides null.

For more information : https://cloud.google.com/firestore/docs/query-data/order-limit-data#java_5

I use following boolean method may be someone else can

for(QueryDocumentSnapshot document: task.getResult()){
    if(document.contains("attending")){
           attending = document.getBoolean("attending");
    }
}
You can check firestore document exists using this,

CollectionReference mobileRef = db.collection("mobiles");
 await mobileRef.doc(id))
              .get().then((mobileDoc) async {
            if(mobileDoc.exists){
            print("Exists");
            }
        });
Related