[英]how to get a username in firestore from another collection with angularfire
how to get a username in firestore from another collection with angularfire如何使用angularfire从另一个集合中获取firestore中的用户名
I have 2 collections我有 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我只能返回 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:但是,基本上,您有两种选择:
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 )在显示
post
之前,您对数据库进行额外查询以获取username
的值,例如afs.collection('users', ref => ref.where('uid', '==', 'user_id))
(见https://github.com/angular/angularfire/blob/master/docs/firestore/querying-collections.md )
This implies an extra read for each post you display这意味着您显示的每篇文章都需要额外阅读
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.这是 NoSQL 世界中的经典方法:您以易于构建和执行查询的方式对数据进行非规范化。
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.但是,只有当您在编写
post
文档时在前端具有username
的值时,这才有可能。 One classical way is to get it from the currentuser
object, via currentuser.displayname
.一种经典方法是通过
currentuser
从当前用户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 ).这种方法的一个副作用是您需要保持值同步(即
user
文档中的值和post
文档中的值)。 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.您不应该害怕重复数据和非规范化您的数据 model。 Here is a "famous" post about NoSQL data-modelling approaches: https://highlyscalable.wordpress.com/2012/03/01/nosql-data-modeling-techniques/
这是关于 NoSQL 数据建模方法的“著名”帖子: https://highlyscalable.wordpress.com/nosql-data
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.