簡體   English   中英

Firestore-DocumentSnapshot和QueryDocumentSnapshot之間的區別

[英]Firestore - Difference between DocumentSnapshot and QueryDocumentSnapshot

該文件說

QueryDocumentSnapshot包含從Firestore數據庫中的文檔讀取的數據,作為查詢的一部分。 該文檔保證存在,並且可以使用getData()或get()方法提取其數據。

QueryDocumentSnapshot提供與DocumentSnapshot相同的API表面。 由於查詢結果僅包含現有文檔,所以exist()方法將始終返回true,而getData()永遠不會為null。

https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/QueryDocumentSnapshot

但這並不能解釋我什么時候應該使用另一個。 我在Collection上的SnapshotListener都嘗試過,並且都可以。

protected void onStart() {
    super.onStart();
    notebookRef.addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(QuerySnapshot queryDocumentSnapshots, FirebaseFirestoreException e) {
            if (e != null) {
                Toast.makeText(MainActivity.this, "Error while loading!", Toast.LENGTH_SHORT).show();
                Log.d(TAG, e.toString());
                return;
            }

            String allNotes = "";

            for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {


                Note note = documentSnapshot.toObject(Note.class);

                String title = note.getTitle();
                String description = note.getDescription();

                allNotes += "\nTitle: " + title + " Description: " + description;

            }

            textViewData.setText(allNotes);
        }
    });
}

如您所說:

QueryDocumentSnapshot提供與DocumentSnapshot相同的API表面

這是因為QueryDocumentSnapshot是DocumentSnapshot的子類。 這意味着可以將每個QueryDocumentSnapshot分配(向下轉換)到DocumentSnapshot類型的變量。 它們的作用完全相同,只是您所聲明的區別在於:

由於查詢結果僅包含現有文檔,所以exist()方法將始終返回true,而getData()永遠不會為null。

因此,如果您要處理QueryDocumentSnapshot,則可以保證exist()方法將返回什么。 如果要處理DocumenSnapshot(實際上不是向下轉換的QueryDocumentSnapshot),則沒有此保證。

我認為您可能只是在強調一個事實是另一個的子類這一事實。 只需使用您在API文檔中看到的那個,就不要將任何內容強制轉換為其他類型,除非您真的知道需要這樣做。

暫無
暫無

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

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