【问题标题】:Get the most recent posts from a list of following firestore从以下 Firestore 列表中获取最新帖子
【发布时间】: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


    【解决方案1】:

    所以,如果我的理解正确,您希望从用户关注的人那里获取帖子,并且您希望将它们按时间排序。那么,我建议你这样做:

    首先,将以下用户列表保存在一个数组中,例如following: ['celeb1','celeb2']

    然后将所有帖子保存在一个集合中,其中包含类似的文档

    {
       content: 'some content',
       author: 'celeb1',
       time: 1598681888  //timestamp or whatever you like
       //some more props
    }
    

    当您想为您的用户获取帖子时,只需这样做

    //Get the array contains all folloing people
    let following = await db.collection('users').doc(userHandle).get();
    
    //Get the first 10 posts from following people
    let posts = await db.collection('posts').where('author', 'in',
    following.data().following).limit(10).orderBy('time', 'desc').get();
    

    查看this 了解有关in 查询的更多信息。

    【讨论】:

    • 感谢您的回答!我不能在下面的数组中最多添加 10 个字符串吗? “使用 in 运算符将同一字段上的最多 10 个相等 (==) 子句与逻辑 OR 组合起来。”就像那个数组不能包含超过 10 个用户一样。
    • 是的,这是此实现的一个限制。老实说,我第一次写答案时并没有考虑过,但我认为这个想法很好。
    • 我想我只是将用户存储为一个数组,并为每 10 个用户进行一次查询,然后从那里获取。使用云功能,以便它可以处理它。
    • 是的,这听起来很合理
    猜你喜欢
    • 1970-01-01
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    • 2013-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多