Firestore - DocumentSnapshot和QueryDocumentSnapshot之间的差异

Flo*_*her 2 android firebase google-cloud-firestore

文件说

QueryDocumentSnapshot包含从Firestore数据库中的文档读取的数据,作为查询的一部分.保证文档存在,并且可以使用getData()或get()方法提取其数据.

QueryDocumentSnapshot提供与DocumentSnapshot相同的API表面.由于查询结果仅包含现有文档,因此exists()方法将始终返回true,而getData()将永远不会为null.

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

但它没有解释何时我应该使用一个而不是另一个.我想无论是在一SnapshotListenerCollection两者工作.

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

Dou*_*son 8

如你所说:

QueryDocumentSnapshot提供与DocumentSnapshot相同的API表面

这是因为QueryDocumentSnapshot是DocumentSnapshot的子类. 这意味着可以将每个QueryDocumentSnapshot分配(向下转换)为DocumentSnapshot类型的变量.他们做同样的事情,除了他们之间的区别,你已经说过:

由于查询结果仅包含现有文档,因此exists()方法将始终返回true,而getData()将永远不会为null.

因此,如果您正在处理QueryDocumentSnapshot,则可以保证exists()方法将返回什么.如果您正在处理DocumenSnapshot(实际上并不是一个已被低估的QueryDocumentSnapshot),则您没有此保证.

我想你可能只是过分重视一个是另一个的子类.只需使用您在API文档中看到的那个,并且不要将任何内容转换为其他类型,除非您确实知道需要这样做.

  • 然而,一个重要的区别是 QueryDocumentSnapshot 通常不包含文档的引用路径,而 DocumentSnapshot 则包含。 (2认同)