【问题标题】:How to check if the field exists in firestore?如何检查该字段是否存在于firestore中?
【发布时间】:2019-10-01 08:03:36
【问题描述】:

我正在检查名为 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");
                }
            }
        }
    });

【问题讨论】:

    标签: java android firebase google-cloud-firestore


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您可以执行以下操作:

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

      来自docs

      public boolean exists ()

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

      【讨论】:

      • 我认为 OP 是在询问如何检查文档中是否存在字段,而不是文档本身。
      • @DanielSaito 是的,但您不能只检索一个字段。您只能检索一个文档,所以这是最好的方法,获取文档然后检查该字段是否为空。
      • 是的,但我认为 OP 在获取文档后正在谈论,在文档列表中执行 doc[index].get(field),其中一些文档有这个 field 而其他文档没有,我认为这是一个很好的收敛到 OP 正在苦苦挣扎的错误的示例哈哈,如果我的解释不是很清楚,对不起。
      【解决方案3】:

      这里是你如何实现它,或者你可能已经解决了,这对于任何寻找解决方案的人来说都是如此。

      根据文档:

      CollectionReference citiesRef = db.collection("cities");
      
      Query query = citiesRef.whereNotEqualTo("capital", false);
      

      此查询返回每个城市文档,其中 capital 字段的值不是 false 或 null。这包括首都字段值等于 true 或除 null 之外的任何非布尔值的城市文档。

      更多信息https://cloud.google.com/firestore/docs/query-data/order-limit-data#java_5

      【讨论】:

        【解决方案4】:
        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");
                    }
                });
        

        【讨论】:

        • 据我了解,OP 是在询问文档中的字段,而不是文档本身,测试文档中是否存在字段。我有同样的问题。
        猜你喜欢
        • 1970-01-01
        • 2018-12-09
        • 2020-09-09
        • 2019-01-21
        • 2022-01-24
        • 2019-10-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多