简体   繁体   中英

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

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 .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM