How to query to Firestore sub document

空扰寡人 提交于 2020-01-25 00:10:34

问题


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?


回答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.




回答2:


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



来源:https://stackoverflow.com/questions/53257112/how-to-query-to-firestore-sub-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!