简体   繁体   中英

How to query to Firestore sub document

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM