Firebase Cloud Firestore Many to Many Relationships

Viewed 14584

How to structure and query data from Firebase Cloud Firestore in a many to many relationship?

I have Companies and Contractors. A Contractor can work for more than one Company and a Company can have multiple Contractors. This is a straightforward many to many relationship. I want to be able to answer the questions about Companies and Contractors:

Given a Company, who are the current Contractors. Given a Contractor what Companies are they working for. What is the right way for structuring the data within Cloud Firestore?

2 Answers

As André Lima has explained in his answer, you can use an Array for the relationships. But I don't think both the collections need to have a field for the array used for mapping. Only one collection needs to have a field for the relationship array.

companies: {
  contractors: ['contractor_id_1', 'contractor_id_2', 'contractor_id_2']
}

While querying, you can use the array-contains operator to filter based on array values.

Example Query (Web):

companiesRef.where("contractors", "array-contains", "contractor_id_1")

You can also use in and array-contains-any operators as per your requirement.

Related