0

Suppose you have a database like this (for convenient showing in GraphQL format)

type User {
  id: ID!
  authenticated: Boolean
}

type Post {
  id: ID!
  user: User # 'Reference' type
}

How could you query posts which are posted by authenticated users?
In SQL you could just join the two tables together and use WHERE clause to specify the condition like this WHERE users.authenticated = true.

I'm wondering how to achieve the same query in Firestore.
If we can't do this in Firestore, what's the solution for such a query?

yaquawa
  • 6,690
  • 8
  • 35
  • 48

1 Answers1

0

Yes, you can query a field using type as ‘Reference’ in Firestore. Reference is a supported data type by Cloud Firestore as in documentation. 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).

Considering a simple example,there are two collections: collection A and collection B. We would like to find out all the docs of Collection A/PQR which is referring to some very specific document Collection B/WJH. Here, we can use Reference that points to the document in Collection B and then use a where clause to filter data on the reference value of Collection A.

Using Javascripts here:

// Create a reference to the specific document you want to search with:
 var reference = db.collection("Collection B").doc("WJH");

 // Construct a query that filters documents matching the reference:
 var query = db.collection("Collection A").where("reference", "==", reference);

You may also refer to a similar Stackoverflow case.

Mousumi Roy
  • 609
  • 1
  • 6
  • Thanks, but this is not what I want. I'm not going to query by a reference itself, but the referenced document's fields(the `authenticated` field in my example). – yaquawa Dec 30 '21 at 15:14