Figen Güngör
Figen Güngör

Reputation: 12559

Friends relationship data models in cloud firestore

I would like to have this relationship model in my cloud firestore models: (https://www.codedodle.com/social-network-friends-database/)

Relationship Model

Status Codes Code Meaning

0 Pending

1 Accepted

2 Declined

3 Blocked

I'm not familiar with Firebase & No SQL a lot. But I see that I cannot make 'or' queries with cloud firestore. How can I convert this to Cloud Firestore Models?

For example in order to get friend list I have to do an or operation in my query:

Friends List

Retrieve all the users’ friends. Here user 1 is the logged in user.

SELECT * FROM `relationship`
  WHERE (`user_one_id` = 1 OR `user_two_id` = 1)
  AND `status` = 1

Upvotes: 0

Views: 637

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599641

Instead of storing the user IDs in two separate fields, you'll want to store them in a single array:

userIds: [1, 2]

With that field in the documents, you can then perform an array-contains query to detect all documents where 1 is part of userIds with:

relationsRef.where('userIds', 'array-contains', 1);

And combined with your other condition:

relationsRef.where('userIds', 'array-contains', 1)
            .where('status', '=', 1)

If you're new to Firestore and NoSQL databases in general, I recommend reading NoSQL data modeling and watching Getting to know Cloud Firestore. A few hours spent on those, will save you a multitude of that time going forward.

Upvotes: 2

Related Questions