Satrogan
Satrogan

Reputation: 489

Trying to retrieve data from firestore

I'm trying to retrieve products posted by all the different users from my firestore database, I want to retrieve all posts from all users and display them on a screen (like a feed screen).

This is what the firestore data looks like: firestore screenshot

the code that i'm using to get this data is :

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

I get that i'm passing userId in there thats why i'm only getting products from one user but what is I want is all products in the database regardless of user. How can this be done?

Upvotes: 0

Views: 91

Answers (2)

Jay Mungara
Jay Mungara

Reputation: 7150

I think you want to fetch all the user products. So, directly referencing "product" node will retrieve all your data regardless of user.

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

Then manage snapShot accordingly.

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 600130

What you're describing is a so-called collection group query. Such queries work based on the collection name instead of their path, so you can query all usersProducts collections with:

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

To read more about this type queries, see the blog post that announced them and their documentation.

Upvotes: 1

Related Questions