簡體   English   中英

關於Firestore查詢數據文檔,特別是DocumentSnapshot

[英]About the Firestore query-data documentation specifically DocumentSnapshot

我想在Firestore查詢數據獲取數據文檔中,在什么情況下document != null將評估為false? 它應該不應該是!document.exists()

DocumentReference docRef = db.collection("cities").document("SF");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document != null) {
                Log.d(TAG, "DocumentSnapshot data: " + task.getResult().getData());
            } else {
                Log.d(TAG, "No such document");
            }
        } else {
            Log.d(TAG, "get failed with ", task.getException());
        }
    }
});

onComplete()回調提供了Task<DocumentSnapshot>的Google Task實例,對此調用getResult()應該返回DocumentSnapshot ,並且永遠不會為null

但是,這激起了我的興趣,因此我做了一些測試:我將OnCompleteListener附加到我不知道的文檔上:

FirebaseFirestore.getInstance()
        .collection("this-does-not-exist")
        .document("neither-does-this")
        .get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    if (task.getResult() == null) Log.d(TAG, "getResult is null");
                    Log.d(TAG, "getResult: " + task.getResult());
                }
            }
});

執行時, task.getResult() == null檢查結果為false ,因此消息“ getResult為null” 不會寫入日志。

但是,從getResult()返回時調用toString() getResult()會引發以下錯誤:

java.lang.IllegalStateException: This document doesn't exist. Use DocumentSnapshot.exists() to check whether the document exists before accessing its fields.

這明確指出要使用exists()而不是空檢查,但是用於“獲取文檔”的文檔說:

注意:如果docRef引用的位置上沒有文檔,則生成的文檔將為null。

此外,除Android和Objective-C外,同一文檔頁面上其他語言的示例都使用exists() 最重要的是:Java示例使用了exists()

 DocumentReference docRef = db.collection("cities").document("SF"); // asynchronously retrieve the document ApiFuture<DocumentSnapshot> future = docRef.get(); // ... // future.get() blocks on response DocumentSnapshot document = future.get(); if (document.exists()) { System.out.println("Document data: " + document.getData()); } else { System.out.println("No such document!"); } 

在這種情況下,我敢打賭這似乎是文檔中的錯誤,我們應該使用document.exists()而不是document != null

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM