Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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   .firestore()   .collection('tickets')   .where('category', '==', categoryDocID)   .get(); 

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.

like image 718
jskidd3 Avatar asked Nov 04 '18 12:11

jskidd3


People also ask

How do I get specific data from firestore?

There are three ways to retrieve data stored in Cloud Firestore. Any of these methods can be used with documents, collections of documents, or the results of queries: Call a method to get the data once. Set a listener to receive data-change events.

How do references work in firestore?

< T > A DocumentReference refers to a document location in a Firestore database and can be used to write, read, or listen to the location. The document at the referenced location may or may not exist. A DocumentReference can also be used to create a CollectionReference to a subcollection.

What is firebase firestore reference data type good for?

Within a project, references can point to any other document in any other collection. You can use references in queries like any other value: for filtering, ordering, and for paging (startAt/startAfter). Unlike foreign keys in a SQL database, references are not useful for performing joins in a single query.


1 Answers

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()    .collection('categories')    .doc('5gF5FqRPvdroRF8isOwd');  const files = await firebase   .firestore()   .collection('tickets')   .where('category', '==', categoryDocRef)   .get(); 
like image 134
Renaud Tarnec Avatar answered Oct 08 '22 22:10

Renaud Tarnec