2

I'm working on an app and I would like to query Firestore sub document. Let me explain further.

  1. I have a collection of documents where cars are stored, each document has a particular car with description.
  2. In each of those documents above, I av a sub collection called user_data which have it's own document where a particular userid of the user who add the car to his wishlist is stored.

Now I want to get the document of cars if a userid is present in its sub collection. In short, I want to get the wishlist of a particular user. I'm using streambuilder with listviewbuilder but the problem is how do I perform this query?

Or is there any simpler way of doing this?

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193

2 Answers2

1

Queries in Firestore are shallow, which means they only get items from the collection that the query is run against. There is no way to get documents from a top-level collection and other collections or subcollections in a single query. Firestore doesn't support queries across different collections in one step. So you cannot get items from a collection based on the items that exist within a subcollection. A single query may only use properties of documents in a single collection.

In short, I want to get the wishlist of a particular user.

So the most simple solution I can think of, would be to add under each user object an array of favorite cars. Your new database structure should look similar to this:

Firestore-root
    |
    --- users
          |
          --- uid
               |
               --- favoriteCars : ["carId", "carId"]

In this way you can query your database to get only the cars a user has marked them as favorite. You can also store instead of those ids in an array, the actual car object. Please see here more details about pros and cons.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Pls I'm developing the app with flutter, how do I combine this with streambuilder. Can u give me a snippet code? I'm thinking of using document reference with the data structure u gave to reference each favourite car to its original document from cars collection – Folarin Opeyemi Nov 12 '18 at 21:45
  • Yes, that's a good idea. In this case, you should make your own attempt given the information in the answer and ask another question if something else comes up. – Alex Mamo Nov 13 '18 at 09:25
0

Currently Firebase Cloud Firestore doesn't support querying with sub collection. You may have to structure your database in way that's possible to query.

  • Store userid in a array in the car document.
  • Use a separate collection to keep the connection between user and cars.

You can checkout this video from Firebase.

Maps, Arrays and Subcollections, Oh My! | Get to Know Cloud Firestore

UdeshUK
  • 972
  • 1
  • 11
  • 19