Wednesday, 13 February 2019

Firebase Firestore - Query for posts in a big collection where groupId should match a value in an array

I am having troubles with firebase using the cloudstore .where query. I want to query a big collection of documents (in my case posts) but I only want to query the posts in which the groupId matches any of the groups that the user is in. The reason for this is that I want to query a combined feed for the user with all the latest relevant data (using orderBy and limit).

I know that I can use array-contains, so I could for instance query all of the posts for user where the user is a member.

firebase.db.collection('posts').where('members','array-contains',firebase.uid)

This would work if I decided to keep track of the members in a group. Problem is if I would change members in a group, I would have to loop through all posts and change the array of members (not really good practice). Better would then be to have the post contain and id of which group it was posted in.

So let's say the user has an array containing all the groups he is in

user.groups = ['companyGroup', '{id}', '{id2}']

I would then like to query through the whole posts collection and get all the documents where the field groupId matches any of the values in user.groups something like this:

firebase.db.collection('posts').where('groupId','==',[any of user.groups])

or maybe the reverse:

firebase.db.collection('posts').where(user.groups,'array-contains','groupId')

^ I have not tried this one but I am certain it doesn't work according to the docs according to

The where() method takes three parameters: a field to filter on, a comparison operation, and a value. The comparison can be <, <=, ==, >, >=, or array_contains.

Is there a possible way to do something like this? I can't really query multiple locations at once and combine them because that defeats the purpose of being able to limit the data and orderBy fields. I understand that I could put a new collection called feed under every user and for every post use a firebase function that pushes to post to the relevant members feed (only the id and latestActivity), but then as soon as that post changes (I am going to use a field called latestActivity to order data according to relevancy, but also when deleting a post) I would need to loop through all docs under every user affected and change the value/delete doc.

Any ideas are greatly appreciated!



from Firebase Firestore - Query for posts in a big collection where groupId should match a value in an array

No comments:

Post a Comment