如何获取当前登录用户正在关注的用户帖子

用户名

我正在使用Cloud Firestore存储我的应用程序数据。我从当前登录的用户遵循的用户那里获取帖子时遇到问题。我已经按这样的数据库结构

Firestore-root
   |
   --- users (collection)
   |     |
   |     --- uid (documents)
   |          |
   |          --- name: "User Name"
   |          |
   |          --- email: "[email protected]"
   |
   --- following (collection)
   |      |
   |      --- uid (document)
   |           |
   |           --- userFollowing (collection)
   |                 |
   |                 --- uid (documents)
   |                 |
   |                 --- uid (documents)
   |
   --- posts (collection)
         |
         ------- postId (document)
                    |
                    |
                    --- uid: user
                    |
                    --- timestamp: 1570044062.261539
                    |
                    --- status: "status"

当我获取供稿的帖子时。我将查询返回的数据分为多个批次,并按时间戳排序该批次。每个批次有10个帖子,但是这些批次不包含来自当前登录用户的用户帖子。它读取当前存储在数据库中的所有帖子,而不管谁在关注谁

postsQuery = db.collection("posts").order(by: "timestamp", descending: true).limit(to: 10)

当用户登录并加载其供稿时,fetchFirstBatch()函数发送对前10个帖子的请求

private func fetchFirstBatch() {
        self.displaySpinner(onView: self.view)
        print("Fetching first batch")
        postsQuery.getDocuments { (snapshot, error) in
            guard let snapshot = snapshot else {
                print("Error retrieving batch: \(error.debugDescription)")
                return
            }

            guard let lastSnapshot = snapshot.documents.last else {
                return
            }

            for document in snapshot.documents {
                let data = document.data()
                let postType = data["post type"] as? String ?? ""

                if postType == PostType.Status.type {
                    let status = data["status"] as? String ?? ""
                    let timestamp = data["timestamp"] as? Double ?? 0
                    let uid = data["user id"] as? String ?? ""
                    let username = data["username"] as? String ?? ""

                    self.posts.append(Post(status: status, timestamp: timestamp, postType: PostType.Status, userId: uid, username: username))
                }
                self.tableView.insertRows(at: [IndexPath(row: self.posts.count - 1, section: 0)], with: .automatic)
            }

            self.lastSnapshot = lastSnapshot

            DispatchQueue.main.async {
                self.tableView.reloadData()
                self.removeSpinner()
            }
        }
    }

一旦用户滚动到包含所有帖子的表格视图的底部,则通过fetchNextBatch()函数获取下一批帖子

private func fetchNextBatch() {
        print("Fetching next batch")
        fetchingBatch = true

        postsQuery.start(afterDocument: lastSnapshot).getDocuments { (snapshot, error) in
            guard let snapshot = snapshot else {
                print("Error retrieving batch: \(error.debugDescription)")
                return
            }

            guard let lastSnapshot = snapshot.documents.last else {
                print("No more batches to fetch")
                self.fetchingBatch = false
                return
            }

            for document in snapshot.documents {
                let data = document.data()
                let postType = data["post type"] as? String ?? ""

                if postType == PostType.Status.type {
                    let status = data["status"] as? String ?? ""
                    let timestamp = data["timestamp"] as? Double ?? 0
                    let uid = data["user id"] as? String ?? ""
                    let username = data["username"] as? String ?? ""

                    self.posts.append(Post(status: status, timestamp: timestamp, postType: PostType.Status, userId: uid, username: username))
                }
                self.tableView.insertRows(at: [IndexPath(row: self.posts.count - 1, section: 0)], with: .automatic)
            }

            self.lastSnapshot = lastSnapshot

            DispatchQueue.main.async {
                self.tableView.reloadData()
            }

            self.fetchingBatch = false
        }
    }

如何附加当前登录用户所关注的所有用户帖子,同时对每批获取的数据进行分页?我要复制的提要结构是Instagram提要。

ian

最好将您的问题分解成较小的部分,因为您提出的问题是您及其实施的全部功能。

我不明白为什么将以下集合与用户的集合分离,然后将它们放在数据模型的顶层,因为基本上在那儿,您已经创建了另一层来向用户文档添加用户关注的子集合。您可以将用户重新定位到下一级用户文档。同样,这还是取决于您是要存储用户(用户关注的人)的全部数据还是要用他们自己的uid填充他们的文档这一事实。

但是,查看数据模型的当前状态类似于以下代码,可以帮助您:

const arrayOfPeopleWhichUserFollows = await db.collection('following').doc(userId).collection('userFollowing').get()
      .then(querySnapshot => {
        return  querySnapshot.docs.map((doc) => {
          return doc.data().uid;
        });
      });


    // you have to measure the size of arrayOfPeopleWhichUserFollows to check whether it exceeds the limitation of 10
    // for using in the "where in" query from firestore
    // then breaks the array into a smaller piece, as small as 10 items per array and the repeat the below part for all the
    // fragmented arrays and append all the results into a single variable

    const firstPosts = await db.collection('posts')
      .where('uid', 'in', fragmentedArrayOfPeopleWhichUserFollows)
      .orderBy('timestamp', 'desc').limit(10);

    const posts = await firstPosts.get()
      .then(querySnapshot => {
        const lastVisible = querySnapshot.docs[querySnapshot.docs.length - 1];
        return querySnapshot.docs.map((post) => {
          return post.data();
        });
        const nextPosts = db.collection('posts')
          .where('uid', 'in', fragmentedArrayOfPeopleWhichUserFollows)
          .orderBy('timestamp', 'desc')
          .startAfter(lastVisible)
          .limit(10)
      });

考虑阅读以下链接:

如何在Firestore中编写查询

从Firebase查询时如何对数据进行分页

如何在Cloud Firestore中管理索引

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何使用Keycloak在Spring Boot中获取当前登录用户?

如何获取服务中的当前登录用户

如何在Django中获取当前登录用户的用户ID?

如何使用Spring Security和Thymeleaf获取当前登录用户的ID

如何在Vue组件中获取当前登录用户的用户对象

流星快捷方式,以获取当前登录用户的个人资料图片,而不管平台如何

XMPPFramework-如何获取当前登录用户的显示名称

如何获取当前Windows登录用户的用户名?

获取与给定模型实例的当前登录用户关系

查找当前登录用户的用户角色

Grails:如何获取当前登录用户的用户名,以及需要进行哪些导入?

Yii获取当前登录用户

如何显示当前登录用户的数据

如何从所有登录用户身份列表中获取当前登录请求的userIdentity?

如何获取当前登录用户authservice的用户名

如何查询关注的用户帖子?

如何在 UWP App 中获取当前登录用户的用户名或 ID

获取当前登录用户的详细信息

如何显示当前登录用户的数据

如何获取当前登录用户

如何获取登录用户ID

获取当前登录用户的名称

如何获取当前登录用户的user_id

实时获取当前登录用户的数据 - Flutter & Firestore

如何使用自定义抽象用户在 django 中获取当前登录用户

需要获取所有登录用户作为对象关注的用户

如何获取与登录用户相关的信息?

如何获取当前Windows登录用户的全名而不是域名

如何获取当前登录用户?Django 模型