ios - 如何获取集合下文档下的数据计数?
问题描述
我有一个名为“用户关注者”的集合。我基本上需要显示关注者的总数。只是无法弄清楚完成块以获得计数。有一些资源可以帮助我计算集合下的文档数量,但是文档中的值呢?这是数据在 Firestore 中的存储方式:
Collection: "user-followers"
Document: "abc"
"user1":1
"user2":1
"user3":1
我想要文档“abc”下的用户数,即 3。
有资源可以获取所有文档的计数,但是文档中的数据计数呢?
解决方案
默认情况下不支持此功能,但您有几种方法可以解决这个问题。(除非您可以查询整个集合以获取记录数……这意味着一切,字面上的一切)
- 云函数
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 等其他工具来跟踪这一点,但它们会花费更多的钱。
我会应用云功能开始。
推荐阅读
- java - 在 groupby 之后获取平均值以获得公平的平衡
- android - 显示通知 - 启用勿扰模式
- flux - 如何根据 Flux 对象是否有元素在 webflux 中返回不同的响应?
- html - 陷入重定向循环
- python - Python Dash 中的多下拉列表错误
- ios - SwiftUI尝试使用MPMusicPlayerController和playbackState
- r - 基于数据框列的条件 str_remove
- docker - 镜像多拱 Docker 映像的正确方法
- angular - 给我的 ngRx 管道无法读取未定义的属性管道
- python-3.x - 无法在 nginx docker 容器中安装 python 3.8.5 版本