skip to Main Content

I am trying to support multiple clients in Firebase with Firestore. And for a collection, each company has one copy. For example, each company has a collection "forms" in such a way: (prefix + collection name)

_c_companyABC_forms

_c_companyXYZ_forms

_c_companyAnyName_forms

There might be 10-20 companies but they all have the same database structure, I just use prefixes to distinguish them.

Is there a way for Firebase Cloud Function to be able to listen to the document change for all the collections above also I can extract the company name from the path, something like below (where I use * as a pseudo-code to indicate any name in that collection name)

exports.formChangeTask = functions.firestore
  .document('_c_*_forms/{formId}')
  .onWrite(async (change, context) => {
      
     const path = context.resource.name.split('/');
     const collectionName = path[0];
     const companyShortName = collectionName.split('_')[2];
}

2

Answers


  1. Why not create a simple form without prefix collection and collect their all documents there? Or create collection with companies and assign to document’s form subcollection with documents?

    You are trying to add extra, useless complexity to your database. If you want to extend database by one client, you will need to add every time extra security rules by your self or create extra complex function that will do it for you every time new client apers not mention that you will need to track somehow all those collections names because just admin SDK can get list of collection names.

    Try to think about collection names as a tables names in a regular database.

    Login or Signup to reply.
  2. The simplest database schema I can think of would be to add all companies into a single collection. The structure might look like this:

    db
    |
    --- companies (collection)
         |
         --- $companyId (document)
               |
               --- name: "ABC"
    

    In this way, you can get all companies in the database, if you need to. You can also get only a company with a specific name using where('name', '==', 'ABC'). If you however, need to add, for example, some forms to each company, then you should simply add a sub-collection under each company document, a case in which the database schema should look like this:

    db
    |
    --- companies (collection)
         |
         --- $companyId (document)
               |
               --- name: "ABC"
               |
               --- forms (collection)
                    |
                    --- $formId (document)
                         |
                         --- name: "Any"
    

    In this way you can always query to get all forms of a specific company and use a collection group query, to get all forms of all companies.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search