【问题标题】:Firestore - Difference between DocumentSnapshot and QueryDocumentSnapshotFirestore - DocumentSnapshot 和 QueryDocumentSnapshot 之间的区别
【发布时间】:2018-09-26 08:22:53
【问题描述】:

文档说

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);
        }
    });
}

【问题讨论】:

  • 我不明白你的问题。您永远不会决定使用哪一个 - API 会告诉您您将获得哪一个。在您显示的代码中,您的侦听器正在接收一个 QuerySnapshot,它产生多个 QueryDocumentSnapshot 对象。 DocumentSnapshot 从来没有出现在这里——你没有同时使用它们。您有一个名为 documentSnapshot 的变量,但这不是一回事。
  • 如果我在 for 循环中将 QueryDocumentSnaptshot 替换为 DocumentSnaptshot,则应用的行为相同。

标签: android firebase google-cloud-firestore


【解决方案1】:

正如你所说:

QueryDocumentSnapshot 提供与 DocumentSnapshot 相同的 API 界面

这是因为QueryDocumentSnapshot 是 DocumentSnapshot 的子类。这意味着可以将每个 QueryDocumentSnapshot 分配(向下转换)到 DocumentSnapshot 类型的变量。除了您所说的它们之间的区别之外,它们的作用完全相同:

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

因此,如果您正在处理 QueryDocumentSnapshot,则可以保证 exists() 方法将返回什么。如果您正在处理一个 DocumenSnapshot(实际上并不是一个被向下转换的 QueryDocumentSnapshot),那么您就没有这个保证。

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

【讨论】:

  • 然而,一个重要的区别是 QueryDocumentSnapshot 通常不包含文档的引用路径,而 DocumentSnapshot 包含。
猜你喜欢
  • 1970-01-01
  • 2020-08-01
  • 2018-10-14
  • 1970-01-01
  • 1970-01-01
  • 2019-11-01
  • 2021-12-25
  • 2020-05-10
  • 2014-09-20
相关资源
最近更新 更多