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

Ash*_*dav 2 java android firebase google-cloud-firestore

假设我有一个文件。我知道它的ID. 现在我想知道该文档中是否存在特定字段。如果没有,我想创建它。是否可以?

PS:我不想将字段名称与我自己的名称放在一起并将该值作为null.

Ale*_*amo 10

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

要解决这个问题,您可以简单地检查无效性,如下所示:

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
                }
            }
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

要将新的特定字段添加到现有文档,请参阅我在这篇文章中的回答。