【问题标题】:Firestore/Flutter: querying document's subcollectionFirestore/Flutter:查询文档的子集合
【发布时间】:2021-04-08 01:11:50
【问题描述】:

我正在开发一个颤振应用程序并使用 Firestore 作为后端: 我的数据库结构是:

  • 用户(集合)
    • userid(用户属性)
    • 书籍(子收藏)
      • booksList(对象数组(或 Firestore 调用它们的地图))

从 booksList 数组中检索每本书的函数是:

Future<List<Book>> bookshelf(String userId) async {
  return await FirebaseFirestore.instance
      .collection('Users')
      .where('userId', isEqualTo: userId)
      .get()
      .then((querySnapshot) => querySnapshot.docs.map((doc) => doc.reference
          .collection('Books')
          .get()
          .then((querySnapshot) => querySnapshot.docs.forEach((doc) {
                var books = doc.data()['bookList'];
                return books
                    .map<Book>((elem) => Book(title: elem['title']));
              }))).toList());

我的问题是我无法返回 Future>;
我试图创建一个数组并在第 12 行向其中添加元素(我实际上是在此处正确获取书籍),但它没有工作,因为 return 语句没有等待查询完成。
基本上,我无法将获得的对象转换为 Future ,因为我需要该功能。 现在我得到一个“MappedListIterable”。
谢谢。

【问题讨论】:

  • 你现在在做什么?
  • @salmansamadi:那是在 java 上,我不太确定如何在 dart 中制作它,因为方法完全不同。
  • @PeterHaddad:我得到一个“MappedListIterable>”

标签: firebase flutter dart google-cloud-firestore


【解决方案1】:

错误是由最嵌套的Promise 回调中的forEach 方法引起的,因为forEach 方法总是返回void,但是应该是Book。嵌套列表也会出现错误,可以通过使用expand方法将嵌套列表展平来解决。我已修改您的代码示例以删除 forEach 方法并减少 Promise 回调嵌套:

Future<List<Book>> bookshelf(String userId) async {
  return await FirebaseFirestore.instance
      .collection('Users')
      .where('userId', isEqualTo: userId)
      .get()
      // Maps each user query snapshot to a list of book query snapshots.
      .then(
        (snapshot) => Future.wait(
          snapshot.docs.map((doc) => doc.reference.collection('Books').get()),
        ),
      )
      // Maps each list of book query snapshots to a list of book document snapshots.
      .then(
        (snapshots) => snapshots.expand((snapshot) => snapshot.docs),
      )
      // Maps each list of book document snapshots to a list of raw books.
      .then(
        (docs) => docs.expand((doc) => doc.data()['bookList'] as List),
      )
      // Maps each list of raw books to a list of books.
      .then(
        (books) => books.map((book) => Book(title: book['title'])).toList(),
      );
}

【讨论】:

    猜你喜欢
    • 2020-12-02
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 2021-09-29
    • 2018-06-19
    • 2020-03-08
    • 2021-04-18
    相关资源
    最近更新 更多