0

I have read this https://firebase.google.com/docs/firestore/solutions/arrays but I still couldn't figure out how it solves the issue of querying not-hardcoded user-generated items in array.

Let's say I have a Party collection:

Party {
  name: "Birthday party",
  invitees: [56448, 869987, 230232, 202030] # user id's of invited people
}

How can I query only parties where I'm in the invitees array without making an index for each possible ID?

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
CodeOverload
  • 47,274
  • 54
  • 131
  • 219

2 Answers2

1

https://firebase.google.com/docs/firestore/solutions/arrays

Limitations The solution shown above is a great way to simulate array-like structures in Cloud Firestore, but you should be aware of the following limitations:

Indexing limits - A single document can have only 20,000 properties in order to use Cloud Firestore built-in indexes. If your array-like data structure grows to tens of thousands of members, you may run into this limit.

So the short answer is no.

If I were using Firebase Database, I would create a cloud function to watch the party/invitees branch on creation and modification, then propagate the invitation to a branch on the userID profile. Because you can be invited and uninvited, the changeset contains old and new and you can remove invitations from people who are in the previous but not in the next.

I haven't explored Cloud Functions for Firestore (yet) but I suspect that you can do something similar.

James Poag
  • 2,320
  • 1
  • 13
  • 20
  • The problem i see is that I'd have to create an index for each possible ID this way, am i wrong? – CodeOverload May 13 '18 at 11:58
  • Who is running the query, the user? Wouldn't the user have his or her ID? – James Poag May 13 '18 at 12:02
  • Yes the user does - but Firestore needs you to create a composite index beforehand for each field you want to query (where) by . `.where('invitees.56448', '==', true)` would require an index called `invitees.56448`, this would be very impractical to have an index for each user – CodeOverload May 13 '18 at 12:05
  • Ok, I see. Hang on. – James Poag May 13 '18 at 12:06
1

If you follow the method described in the documentation you point to (i.e. https://firebase.google.com/docs/firestore/solutions/arrays) and instead of storing the users in an array you save an object like

Party {
  name: "Birthday party",
  invitees: {
        "56448": true,
        "869987": true,
        "230232": true,
        .....
       }
}

you will be able to query like

var yourUserID = .....;  //e.g. '869987'
db.collection('invitees')
    .where('invitees.' + yourUserID, '==', true)
    .get()
    .then(() => {
        // ...
    });

And as the doc says "This technique relies on the fact that Cloud Firestore creates built-in indexes for all document fields, even fields in a nested map.", so no worries for maintaining the indexes.

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121