简体   繁体   English

如何检查特定Firestore文档中是否存在特定字段?

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

Lets say I have a document. 可以说我有一个文件。 I know its ID . 我知道它的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 . PS:我不想将字段名与我自己的字段一起放置,并将该值设置为null

How to check whether a particular field exist in a particular firestore document? 如何检查特定Firestore文档中是否存在特定字段?

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 . 要将新的特定字段添加到现有文档中,请参阅我在这篇文章中的回答。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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