0

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<(long)task.getResult().get("no_of_products");x++){ if(task.getResult().get("productID_"+x)==null){ continue; }else{ //some code } } } 

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

6
  • should I just write like this ? if(task.getResult().get("product_ID")==null){ continue; } Commented Sep 17, 2020 at 14:47
  • 1
    do you want to check if a document exists or a key value par exists ? Commented Sep 17, 2020 at 14:59
  • I want to check if key value pair exists or not I don't need about document Commented Sep 17, 2020 at 15:01
  • the above for loop itself retrieving all the fields in that document Commented Sep 17, 2020 at 15:04
  • 1
    I think it would help to know which field you're talking about; do you mean Fields or 'a'/'b' etc? I think you mean you want to see if for example, field 'a' exists and if so, do one task and if not, do another. However, how you determine if it exists will depend on if you're reading in the data and checking it in code, or if you want to directly check in in Firestore. It may help even more to get a better idea what your actual Firestore structure looks like - can you include a screenshot of that? Commented Sep 17, 2020 at 19:16

1 Answer 1

1

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("PRODUCTS") .orderBy("no_of_products") .startAt(null); 
Sign up to request clarification or add additional context in comments.

3 Comments

NO I cant understand you. what I meant is Task<DocumentSnapshot> task is the document in which I'm using the field no_of_products so that I can iterate through that range.In the same document there are productID key value pairs, some of the key value pairs are missing so upon iterating that for loop I was retrieving the key value pair which doe's not exists. so I want to check that key value pair if exsits only I want to continue to next lines of code
I'm not sure what you mean there. Did you try the code I gave? It will return only documents that have a no_of_products field.
yeah it helped me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.