【问题标题】:Trying to retrieve data from firestore尝试从 Firestore 中检索数据
【发布时间】:2020-04-04 06:46:19
【问题描述】:

我正在尝试从我的 firestore 数据库中检索所有不同用户发布的产品,我想检索所有用户的所有帖子并将它们显示在屏幕上(如提要屏幕)。

Firestore 数据如下所示:

我用来获取这些数据的代码是:

static Future<List<Product>> getProducts(String userId) async {
    QuerySnapshot productSnapshot = await productsRef
        .document(userId)
        .collection('usersProducts')
        .orderBy('timestamp', descending: true)
        .getDocuments();
    List<Product> products =
        productSnapshot.documents.map((doc) => Product.fromDoc(doc)).toList();
    return products;
  }

我知道我在那里传递了 userId,这就是为什么我只从一个用户那里获取产品,但我想要的是数据库中的所有产品,而不考虑用户。如何才能做到这一点?

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:

    您所描述的是所谓的集合组查询。此类查询基于集合 name 而不是它们的路径,因此您可以查询所有 usersProducts 集合:

    Firestore.instance.collectionGroup('usersProducts').getDocuments()
    

    要了解有关此类型查询的更多信息,请参阅blog post that announced them 及其documentation

    【讨论】:

      【解决方案2】:

      我认为您想获取所有用户产品。因此,无论用户如何,直接引用“产品”节点都会检索您的所有数据。

      QuerySnapshot snapShot = await Firestore.instance.collection("products").getDocuments();
      

      然后相应地管理 snapShot。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-06-16
        • 2021-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-22
        相关资源
        最近更新 更多