Matheus
Matheus

Reputation: 99

How to get documents in which object contains key in Firestore?

I'm creating an Ionic application using Firestore with Angularfire2.

My database structure is as follows:

- creators
  - CREATOR_ID
    - name (string)
    - description (string)
    - posts (map)
      - category1 (array)
        - [POST1, POST2, POST3]
      - category2 (array)
        - [POST3, POST4, ...]

A creator is able to create posts/articles. And when a creator creates an article he's able to specify which categories that post belongs to!

The thing about the aplication though is, when a user wants to filter by category, it will bring all the CREATORS that contain at least one post in the category the user selected (instead of bringing all the articles in that category).

So, based on the structure above I tried the following:

this.afs.collection<Creator>('creators', ref => ref.where("posts.category1", '>', ""));

But it returns nothing!

Do you guys have any suggestions?

Thanks!

Upvotes: 0

Views: 1300

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

As I see in your database schema, your category1 and category2 are arrays. The following where() function call:

.where("posts.category1", '>', "POST1")

Would have been worked, if your categories (category1 and category2) would have been of type Map and not arrays and you would have been queried for a particular post. To solve this, there are two approaches:

The first one would be to change the type of your categories from array -> map and use the above line code and the second one would be to use:

.where("posts.category1", , "array-contains", "POST1")

But note, none of the above approaches will help you find if an array contains at least one element. For that, you should add a listener and check if that particular array/map exists.

See here more informations.

Upvotes: 1

Related Questions