简体   繁体   中英

how to get a username in firestore from another collection with angularfire

how to get a username in firestore from another collection with angularfire

I have 2 collections

-users
--username
--uid

and

-post
--title
--user_id

How to get the username when displaying all posts?

I could only return the user_id

You didn't share your existing code for displaying all posts, so it is difficult to give your the exact code to add...

But, basically, you have two options:

Lookup the username in the users collection

Before displaying a post , you do an extra query to the database to get the value of the username , like afs.collection('users', ref => ref.where('uid', '==', 'user_id)) (See https://github.com/angular/angularfire/blob/master/docs/firestore/querying-collections.md )

This implies an extra read for each post you display

Save the username together with the userid when you save the post document

This is a classical approach in the NoSQL world: you denormalize your data in such a way your query is easy to build and execute.

More concretely it means that your posts collection would be like:

-post
--title
--user_id
--username

However, this is only possible if you have, in your front-end, the value of username when you write the post document. One classical way is to get it from the currentuser object, via currentuser.displayname .

One side effect of this approach is that you need to keep the values in sync (ie the one in the user document and the ones in the post document s ). However, in your specific case, we can probably make the assumption that the username is not going to change very frequently...


You should not be afraid to duplicate data and denormalize your data model. Here is a "famous" post about NoSQL data-modelling approaches: https://highlyscalable.wordpress.com/2012/03/01/nosql-data-modeling-techniques/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM