Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding all docs with specific reference in Cloud Firestore

On Cloud Firestore I have documents with reference to another document this way:

Reference from collection A to B

In my example, document Collection A/WJQ9yx67RrqHWQoEp0e2 is referring to document Collection B/rFOEwdw5go4dbitOCXyC, but there of course, could be infinitely docs referring to one mentioned.

Now I would like to find out all the docs of Collection A which are referring to this very specific document Collection B/rFOEwdw5go4dbitOCXyC.

How is this possible? How I can achieve this?

Documentation of Firebase is bit unclear with this.

like image 956
Petja Avatar asked Oct 25 '17 13:10

Petja


1 Answers

You're right, there's unfortunately no example of actually making use of a Reference data type in the documentation, in fact the only a mention of it is in the Supported Data Types section.

Ultimately though, a Reference can be used just like any other data type available in Firestore, so can be used to filter & sort data too.

To achieve what you're after, you would need to construct a 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. For example in JavaScript:

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

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

Looking at the source for isEqual() in the Firebase JavaScript SDK, comparing of a Reference (extends Query) is performed by simply checking that the paths match:

  isEqual(other: Query): boolean {
    // [...]
    const sameRepo = this.repo === other.repo;
    const samePath = this.path.equals(other.path);
    const sameQueryIdentifier =
      this.queryIdentifier() === other.queryIdentifier();

    return sameRepo && samePath && sameQueryIdentifier;
  }

This would seem to be much like calling toString() on both and comparing the string values.

I produced a similar example yesterday which lead me to test the possible uses of storing a Reference, so that may also apply here.

like image 98
Grimthorr Avatar answered Oct 17 '22 03:10

Grimthorr