我有一个 posts
我的应用程序存储用户所有帖子的集合,具有以下数据结构:
+ uid (the user id of the creator)
+ text-content : String
+ tagged-users: [String]
+ assigned-media: [{"downloadUrl": String, "storageLocation": String}]
+ type: String
+ typestamp: Timestamp
+ Likes
+ uid (the user id of the liking person)
+ timestamp: Timestamp
+ postId (optional, depending on the results of the collection group queries)
现在,我想向我的用户显示此集合的所有帖子;但仅限于,如果用户关注创建帖子的人,即
uid
邮政文件的领域适合。我知道如果用户只关注一个人,查询集合很简单,即我有一个简单的
where
条款。但是:如果我的用户 怎么办?关注 10.000 人 或者更多?我该如何查询?另外,我应该如何存储
followings
,即用户关注的人?使用简单的数组似乎不适合我,但使用所有其他选项,我无法查询来自我关注的人的帖子的帖子集合。我会很感激我能得到的每一个帮助!
最佳答案
这是一个复杂的问题(我不是 100% 确定这是问它的正确地方),我会尽我所能来帮助你开始,
免责声明,这可能适用于您的用例,也可能不适用于您的用例
将您的服务分为 3 个集合:
- 用户
- 追随者
- 帖子
用户 集合非常简单,您只需要文档 ID(您已经拥有它)。
{
"andyIsTheBest": {
uid: `andyIsTheBest`
// ...
},
"sophieTheBest": {
uid: `sophieTheBest`,
// ...
},
"andyTheWorst": {
uid: `andyTheWorst`,
// ...
},
}
关注者 镜像用户的文档 ID,它应该如下所示:
{
"andyIsTheBest": {
last_post: 2019,
followers: [
'sophieTheBest', 'andyTheWorst'
],
recent: [
{
post_id: 112233, // from the post collection
seq: 2019
}
]
}
}
最后,帖子 集合看起来像这样:
{
"112233": {
seq: 2019,
body: `blabla the cool post`
author: `andyIsTheBest`
}
}
重要的是,请注意序列
seq
号码也是last_post
,你可以通过云函数更新这个值,以便你跟踪它,然后剩下的只是实现细节:const remove = firebase.firestore.FieldValue.arrayRemove
const union = firebase.firestore.FieldValue.arrayUnion
const follow = async (toFollow, user) => {
await db
.collection('followers')
.doc(toFollow)
.update({ users: union(user) });
}
const unfollow = async (toUnFollow, user) => {
await db
.collection('followers')
.doc(toUnFollow);
.update({ users: remove(user) });
}
const feed = async (user) => {
await db.collection(`followers`)
.where(`followers`, `array-contains`, user)
.orderBy(`last_post`, `desc`)
.limit(10)
.get()
// do whatever business logic you need down here
}
基本上这样,如果您有 1 万亿或 1 万亿并不重要,查询应该没问题。
我没有涵盖很多细节,但这应该可以帮助您入门。
希望这有帮助。
感谢在我公司实现此功能的同事^^
关于firebase - Firestore 社交媒体模型结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58043579/