Reputation: 13
I am using firebase as a backend for my Android App. And this app is a social media app where users can post, comment & like. so I am storing user data in user_collection
and this collection is secured by security rules where if uid == auth.uid
(any user can only access data of himself).
Now in this app when a user post something every user can see this post. And in post_collection I am saving userId in post_doc.
So the problem is I need to show name of user to other users and I have only userId but the problem is a user can't get name of other user by uid beacuse of security rules. now I have to solutions for this please tell me which one is better or you can also suggest any other solutions also?
I can use cloud functions getUserNameById()
(Problem : I need to call this function very frequently in feed when user scroll)
I can store name also in post_doc
(problem : when user changes his name then It will show old name in old post)
Thanks for you kind help
Upvotes: 1
Views: 2194
Reputation: 598740
In a scenario like the one you describe, I would typically store the user name in each post doc. I would also ignore updates to the name, as I think of the user name in the post doc as a historical value: this is the name the user had when they posted this. Now you may want different behavior of course, in which case I recommend reading: How to write denormalized data in Firebase
Your approach with Cloud Functions is fine too, and quite common in some situations. But I tend to only use Cloud Functions for reading data, it the read operation itself is particularly complex, which isn't the case here. In a case like this, I'd recommend coming up with a data model that allows the use-case and security you want.
For example: if you create a collection usernames
where each document has the UID as its document ID, and then contains a single field with the username for that UID, you could implement the lookup of the user name through Firestore.
So you could have:
/users/$uid
./usernames/$uid
./users/$uid
is written and that updates /usernames/$uid
./usernames/$uid
document, or even to the entire /usernames
collection in one go if needed.This way the names can be cached on the client, and continue to work when the app is offline, unlike in your approach with a Cloud Function that looks up the user name.
Upvotes: 3
Reputation: 124
Consider the solution: whatever public data you need (author name, author userpic link etc) just save it with the post at the time it had created. So your Message Pojo will looks like:
etc..
and just display this name (authorName). It will be the bad way to go any time to User_collection folder to take the name even if there are would be not strict security (becouse it takes time and document reads)
Upvotes: 1