如何检查firestore中是否存在该字段?

Mar*_*nas 10 java android firebase google-cloud-firestore

我正在检查调用的布尔字段是否attending存在,但我不知道该怎么做。

有没有类似的功能.child().exists()我可以使用?

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");
                }
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

Pet*_*dad 5

您可以执行以下操作:

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

来自文档

public boolean exists ()

如果该文档存在于该快照中,则返回 true。


Dou*_*son 4

您现在所做的事情是正确的 - 您必须阅读文档并检查快照以查看该字段是否存在。没有比这更短的方法了。