0
votes

I want to query all users that a user (user1) is friends with, in one query with firestore.

Currently, I have a "friends" field in each user object, so to get the users who are friends w user1, I call:

friendsOfUser1 = db.collection('users').where('friends', 'array-contains', user1).stream().

This works well when users only have < 100 friends, but after that the user objects get very large since the user.friends array has many values. This makes receiving user objects expensive.

Is there a way to store the friends array outside of the user documents while still being able to query a user's friends in one query? This is what the structure is now:

user1: {friends: ["user2", "user3", "user7", "user9"], name: "John Sci"}

user2: {friends: ["user1", "user4", "user8", "user12"], name: "Elmo Square"}

user3: {friends: ["user1", "user7", "user9"]}

so db.collection('users').where('friends', 'array-contains', user1).stream() will give [user2, user3].

1
Please before you post look at the formatted version of your post below the edit box. Read the edit help re inline & block formats for code & quotations.philipxy

1 Answers

3
votes

The scalable alternative to storing strings in an array is to store the same strings in separate documents, typically as a subcollection of the main document.

/users
    /{uid}
        /friends
            /{friendId1}
            /{friendId2}
            /{friendId3}

In order to find out if user1 has user2 as a friend, all you have to do here is get the document using the IDs of the two users: /users/user1/friends/user2. If the document exists, there is a relationship.