How to query based on requirements?

Viewed 62

I am creating an app where people can schedule appointments with professionals. When the professionals are creating an account, sometimes the service they want to offer may require a work permit/license in certain locations.

I've been trying to create a database design on Firebase Firestore where based on the location, and type of service, I can get a list of requirements (e.g. work permit or insurance).

It's also worth noting that not all services are available in all locations.

So far the design I have is the following (those in brackets are collections):

(locations)
    United States
        (cities)
            New York
                (categories)
                    Home Improvement
                        (services)
                            House Cleaning
                            - array of licenses/permits required

The user's country and city are already known and stored in the user's profile document.

I am pretty new to all of this but even I can see that this is very repetitive as I'd have to do the same thing for every single location.

Any help is appreciated thank you!

1 Answers

A single collection "services" with documents containing every detail about a service should do it.

services -> {serviceID}

A document of a service may look something like:

{
  serviceID: "service1234",
  category: "Home Improvement",
  location: "United States",
  city: "New York",
  requiredPermits: []
}

Now you can easily query services based on location, category or any other field:

const servicesCol = firebase.firestore().collection("services") 
const servicesInNYC = await servicesCol.where("city", "==", "New York").get()

// for fetching services in multiple cities
await servicesCol.where("city", "in", ["New York", "Washington DC"]).get()

Additionally, if a service can have multiple categories then you can store an array of categories in their documents and then fetch a specific category like this:

await servicesCol.where("categories", "array-contains", "Home Improvement")

Similarly you can query for services that require a specific license/permit (make sure you have those in an array in the document).

Edit: If a single service can have have multiple locations with different permits required then you can remove requiredPermits field and move location to a sub-collection as follows:

services -> {serviceID} -> locations -> {locationID}

Each document in locations sub-collection may look like:

{
  country: "United States",
  city: "New York",
  permits: [....]
}

Now you can query locations of a service with a specific permit:

const serviceLocations = await servicesCol.doc("serviceID").collection("locations").where("permits", "array-contains", "permit1ID").get()

// To get services with a specific location/permit
const locationsGroup = firebase.firestore().collectionGroup("locations")
const snap = await locationsGroup.where("permits", "array-contains", "permit1ID").get()
Related