2

Lets say I have a document. I know its ID. Now I want to know whether inside that document a particular field exist or not. And if not, I want to create it. Is it possible?

PS: I don't want to put the field name with my own and put that value as null.

Ashish Yadav
  • 543
  • 2
  • 7
  • 30

1 Answers1

10

How to check whether a particular field exist in a particular firestore document?

To solve this, you can simply check for nullity like this:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
DocumentReference docIdRef = rootRef.collection("yourCollection").document("yourDocumentId");
docIdRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {
                if (document.get("yourField") != null) {
                    Log.d(TAG, "your field exist");
                } else {
                    Log.d(TAG, "your field does not exist");
                    //Create the filed
                }
            }
        }
    }
});

To add a new particular field to an existing document, please see my answer from this post.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193