I've been struggling for a few evenings now so I hope someone can help me, it doesn't sound too complicated to me. I'm using a webhook from an external party which fires to Firebase functions everytime a change is made to an account. When this is triggered, it needs to search and update the relevant Firebase object.
My database structure is as follows:
- Users (collection)
- user (document) < Includes the customerId from the webhook
- Companies (collection)
- company (document) < Includes the companyId from the webhook
To get the relevant user I've done: const userRef = db.collection('Users').where('customerId', '==', 'webhook.customerId').get();
This works when querying the relevant user, but the next step is to search the right company document in the collection Companies
. This is the part where I get stuck.
To accomplish this I've tried to string it together (lol) so like: const userRef = db.collection('Users').where('customerId', '==', 'webhook.customerId').doc().collection('Companies').where(etc... etc...
this didn't work.
I also tried const companiesRef = db.collectionGroup('Companies').where('companyId', '==', 'webhook.companyId').get();
But that returns a 500 internal server error.
Any way I can query search nested documents in Firebase functions?
CodePudding user response:
What you're looking for is a collection group query, which allows you to query across all collections with a specific name (such as all Companies
in your case).
Firestore queries can only contain conditions on the documents that they return though, so you won't be able to check the customerId
field in the Users
documents. Instead, you'll need to replicate the customerId
value in each Companies
document, so that you can include it in the collection group query.
Once you do that, the query would become something like:
db.collectionGroup('Companies').where('customerId', '==', '...').where(...).get()