Home > Blockchain >  How to query a document and sub-document together Firestore?
How to query a document and sub-document together Firestore?

Time:11-12

My data structure looks something like this:

- posts (collection)
  - post (document)
      title
      description
      labels
      vote counts
      author
      author choice
      - votes (collection)
         - vote (document)
            choice

I need to write a query so that I find a post under the collections document where author != the user's UID, author choice == null, and category == any of some values (that I have no trouble with) but also where a document with the user's UID doesn't exist in the votes sub-collection.

CodePudding user response:

Firestore queries can only filter on values in the documents that they return. There is no way to have a condition on documents from a subcollection of those documents.

My preferred solution is to include information about the existence of the UIDs that exist in the votes subcollection in the parent document too, update that with every vote that is written, and then query on that new field.


Firestore queries also can only query on values that are present in a document. Values that don't exist are not in any index, so can't be part of a query condition.

That is tricky here as you want to test for the absence of a value. I also suspect that your list of UIDs is dynamic, so you'd have to update every parent document whenever a user is added.

So alternatively, you will have to retrieve the documents regardless of the existence in votes and then perform the additional filtering in your application code.

  • Related