首页 > 解决方案 > 如何获取集合下文档下的数据计数?

问题描述

我有一个名为“用户关注者”的集合。我基本上需要显示关注者的总数。只是无法弄清楚完成块以获得计数。有一些资源可以帮助我计算集合下的文档数量,但是文档中的值呢?这是数据在 Firestore 中的存储方式:

Collection: "user-followers"
 Document: "abc"
  "user1":1
  "user2":1
  "user3":1

我想要文档“abc”下的用户数,即 3。

有资源可以获取所有文档的计数,但是文档中的数据计数呢?

标签: iosswiftfirebasegoogle-cloud-firestore

解决方案


默认情况下不支持此功能,但您有几种方法可以解决这个问题。(除非您可以查询整个集合以获取记录数……这意味着一切,字面上的一切)

  • 云函数
 import * as functions from 'firebase-functions' 
 import * as admin from 'firebase-admin' 
 const firestore = admin.firestore()
 const counterRef =  firestore.collection(`counters`)
 export const keepCount = functions
  .firestore.document(`user-followers/{doc}`).onWrite(async (change, _context) => {
    const oldData = change.before
    const newData = change.after
    const data = newData.data()

    if (!oldData.exists && newData.exists) {
        // creating
        return counterRef.doc(`user-followers`).set({
          counter: firebase.firestore.FieldValue.increment(1)
        })
      } else if (!newData.exists && oldData.exists) {
        // deleting
        return return counterRef.doc(`user-followers`).set({
          counter: firebase.firestore.FieldValue.increment(-1)
        })ID)
      } else  {
        // updating - do nothing
        return Promise.resolve(true)
    }
})

现在您只需要获取counters集合,文档值是您的集合名称user-followers,道具是计数器......您可以将此模式应用于跟踪计数器所需的所有集合......

  • 其他第三方缓存工具

你总是可以使用 algolia 或 redis 等其他工具来跟踪这一点,但它们会花费更多的钱。

我会应用云功能开始。


推荐阅读