0
votes

I have data in firestore in following structure:

directory---
           |---randomDoc1---
           |                 |---contacts--
           |                               |---9212345677--
           |                               |              |---name: abc
           |                               |
           |                               |---8564224455
           |---randomDoc2---
                              |---contacts--
                                           |---9212456677--

I want to query on nested directory->randomDoc->contacts->923436475

If i have 9212345677 a contact number (in contacts collection doc1) and i want to query on directory collection for this 9212345677 number, and get all randomDocs in which this number exists.

for example randomDoc1 & randomDoc3 's contacts collection contains this number, it should return me both randomDoc1 & randomDoc3.

Following is what i am trying:

admin.firestore().collection("directory4").where('id', '==', mobileNo).limit(20).get().then(function(docsSnapShot){
    if (docsSnapShot.size > 0) {
        //print all docsSnapShot
    }else{
        //contact number do not exist in any of collections
    }
});
1

1 Answers

1
votes

It is not currently possible to run a query across multiple sub-collections.

De-normalise

One solution to this, would be to de-normalise this data, with either the contacts documents in their entirety or use a reference to point to the original document.

Add directory references to a users collection

Create a users collection and within each user document, have a directoryDocs collection. Each time a new contact is added to a directory document, trigger a Cloud Function to copy the document reference to the users/{userId}/directoryDocs collection.