如何在使用 Firebase 时检查特定文档中是否存在某个字段?

huangapple go评论55阅读模式
英文:

How could I check if a field exists or not in a particular document when using firebase?

问题

在Firebase Firestore中,我有一个集合及其相应的文档,如下所示:

PRODUCTS
    使用自动生成的ID的文档
        字段:
               a
               b

我想要检查该文档中字段是否存在:

例如,如果字段a存在,则执行某些代码;如果不存在,则执行其他代码。
if (task.isSuccessful()) {
   for (long x = 0; x < (long) task.getResult().get("no_of_products"); x++) {
      if (task.getResult().get("productID_" + x) == null) {
        continue;
      } else {
         //某些代码
       }
   }
}

这种方式是否正确用于检查文档中的字段是否存在?

英文:

In Firebase Firestore I Have a Collection and its corresponding document like

PRODUCTS
		Document with AutoId
							Fields:
                                   a
                                   b

I want to check if the field exists or not in that document

Ex- if field a exists some code will execute if not exists some other code will execute
if(task.isSuccessful()){
   for(long x=0;x&lt;(long)task.getResult().get(&quot;no_of_products&quot;);x++){
      if(task.getResult().get(&quot;productID_&quot;+x)==null){
        continue;
      }else{
         //some code
       }
   }
}

is this the correct way to check if the field exists in a document or not ?

答案1

得分: 1

如果您只想检索字段存在的文档,而不管其具体值如何,您可以在查询中使用 startAt 条件:

db.collection("PRODUCTS")
  .orderBy("no_of_products")
  .startAt(null);
英文:

If you only want to retrieve documents where the field exists, no matter what value it has, you can use a startAt condition on your query:

db.collection(&quot;PRODUCTS&quot;)
  .orderBy(&quot;no_of_products&quot;)
  .startAt(null);

huangapple
  • 本文由 发表于 2020年9月17日 22:38:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/63940447.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定