Querying by a field with type 'reference' in Firestore

I have a collection called 'categories' containing a single document with ID: 5gF5FqRPvdroRF8isOwd.

I have another collection called 'tickets'. Each ticket has a reference field which assigns the ticket to a particular category.

The field in the tickets collection is called 'category' and has a field type of reference.

In the code below, categoryDocId is the document ID of the category I want to query by.

const categoryDocID = `5gF5FqRPvdroRF8isOwd`;

const files = await firebase
  .where('category', '==', categoryDocID)

Why does files.length return 0?

For testing, I changed the category field type to string, and set it to the category ID instead of a direct reference. This correctly returned tickets assigned to the category, which leads me to believe it's something about how I'm querying a reference field.



As you will read here in the doc, the Reference Data Type is used to store DocumentReferences.

If you want to use it in a query, you cannot use a simple string, neither the UID of the document (i.e. '5gF5FqRPvdroRF8isOwd'), nor the string value that is stored in the field (i.e. '/categories/5gF5FqRPvdroRF8isOwd').

You have to build a DocumentReference and use it in your query, as follows:

const categoryDocRef = firebase.firestore()

const files = await firebase
  .where('category', '==', categoryDocRef)


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.