【发布时间】:2020-12-17 22:55:12
【问题描述】:
我正在尝试获取用户关注的人的帖子列表,该列表按帖子的发布时间排序。因此,无论谁发帖,只要用户关注他们,就会首先看到来自该用户集合的最新帖子。我试过这个(不完全正确,只是想把概念弄下来):
// get all the users you are following -- this will count for a lot of reads if they follow 3000 people
const following = await db
.collection('users')
.doc(userHandle)
.collection('following')
.get()
// get the first 10 posts from those users ordered by recently posted
const promises = following.map((doc) => {
return db
.collection('posts')
.orderBy('createdAt', 'desc')
.where('userHandle', '==', doc.data().userHandle)
.limit(10)
.get()
.then(async (data) => {
return data.docs.map((doc) => {
return {
postId: doc.id,
userHandle: doc.data().userHandle,
userImageUrl: doc.data().userImageUrl,
imageUrl: doc.data().imageUrl,
likeCount: doc.data().likeCount,
};
})
})
});
Promise.all(promises)
.then((posts) => {
res.json(posts);
})
上述概念的问题...如果用户关注了一群用户,这将返回很多帖子。该限制仅适用于可以在该页面上返回的一个用户的帖子数量。它还将返回一个用户最近到最旧的 10 个帖子,然后返回下一个用户最近到最旧的 10 个帖子,即使有更多最近的帖子。我正在考虑添加一个计数器,如果返回的帖子数量超过 10,则停止该函数并仅返回这 10 个,但是在函数返回 null 之前我在承诺之前遇到了问题,所以这就是为什么我在我返回所有内容时'我完成了使用 promise.all 的循环。这行得通吗?这可能会解决限制问题,但无法从当前用户关注的用户集合中获取绝对最新的帖子。我希望firestore有一个大查询,我可以在其中获取所有最近的帖子,这些帖子的用户名与以下数组中的一个用户名匹配(可以从上述代码顶部的以下函数返回)。可以肯定的是,如果我只是将用户名字段转换为数组,我只能检查 10 个值。
【问题讨论】:
标签: node.js firebase google-cloud-firestore promise