0

Recently, I decided to migrate my Firebase database to Cloud Firestore. I assumed that it is gonna be a huge improvement on Realtime database but I am afraid it is not. Anyways, I came to a situation in which I want to be able to filter the elements in a sub-collection of a document.

My structure is as follows:

Mailboxes: [
    {
        id: vhR4bfqyo9Uqn2ONbgPv,
        address: "Address 1",
        packages: [
            {
                id: qyo9Uqn2vhR4bfqy,
                value: "0011"
            },
            {
                id: 9Uqn2qyovqyhR4bf,
                value: "0022"
            }
        ]
    },
    {
        id: BBR4bfqyo9Uqn2ONbEpn,
        address: "Address 2",
        packages: [
            {
                id: qn2vhR4bfqyqyo9U,
                value: "0066"
            }
        ]
    }
]

Imagine I have the value of a package and I want to be able to see if this package exists in mailbox with id vhR4bfqyo9Uqn2ONbgPv.

What I've tried so far is the following (and some variations of it):

db.collection('Mailboxes').doc('vhR4bfqyo9Uqn2ONbgPv').listCollections().then(collections => {
    let collRef = collections.find("id", "==", "packages");
    // And, from here on, I assume I will be able to filter the items in the collection somehow.
    return 0;
});

But, then I get an error in my Firebase cloud function saying:

TypeError: id is not a function at Array.find (native) at db.collection.doc.listCollections.then.collections

user2128702
  • 2,059
  • 2
  • 29
  • 74
  • Based on this answer from Doug, I think you may have to replicate your package keys as an array directly inside your mailbox object: https://stackoverflow.com/questions/55554162/how-do-i-use-array-contains-for-array-containing-map – charles-allen Oct 28 '19 at 05:57

1 Answers1

1

Here, packages is an array and not a Firestore sub-collection per se.

With a sub-collection your query would look like:

db.collection('Mailboxes').doc('vhR4bfqyo9Uqn2ONbgPv')
.collection('packages').where('value','==', '0022').get()

If I understand your use case correctly...

Olivier Lépine
  • 618
  • 5
  • 14
  • Well, It looks like an array but it really is a sub-collection on Firebase. I just wanted to represent it kind of like JSON for reading ease. – user2128702 Oct 28 '19 at 08:58
  • Fair enough, this crossed my mind. I don't understand why you use listCollections since you have the id of the mailbox that you want to query... – Olivier Lépine Oct 28 '19 at 10:01