【问题标题】:Firestore - How to find the count of documents that can be fetched using a query without really fetching all documents? [duplicate]Firestore - 如何在不真正获取所有文档的情况下找到可以使用查询获取的文档数量? [复制]
【发布时间】:2020-11-04 15:52:53
【问题描述】:

实际上我想为我的网站创建一个管理面板,我需要显示今天(或上周)注册的用户总数。我想获取今天在 users 集合中创建的用户文档的数量。我在每个用户文档中都有一个 createdOn 字段。

我可以这样做吗:

admin.firestore()
  .collection('user')
  .where('createdOn', '>', <today's midnight timestamp here>)
  .count()

比如有没有什么技巧/解决方案可以在不实际获取文档的情况下获取文档数量。

【问题讨论】:

标签: node.js google-cloud-firestore firebase-admin


【解决方案1】:

由于 Firestore 中没有 COUNT()(目前),您不得不查询您的文档以计算或维护全局或基于参数的记录总数。

有一个 extension 可以做到这一点,但我在配置它时遇到了麻烦。

我个人使用一个简单的云函数,我知道它并不完全防弹,但足以为我提供一个 dbutils 集合,我可以在其中存储任何集合的最新计数。我还维护count 子集合来存储同一集合的记录数,但带有查询参数。非常有必要提出一个 REST API...

import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'

export const dbutils = functions
   .firestore.document('/{collection}/{id}')
   .onWrite((change, context) => {
      const db = admin.firestore()
      const docRef = `dbutils/${context.params.collection}`
      let value = 0

      if (!change.before.exists) {
         value += 1 // new record
      } else if (!change.after.exists) {
         value -= 1 // deleted record
      }
      // ignore last case which is update

      if (value !== 0) {
         db.doc(docRef)
            .set(
               {
                  count: admin.firestore.FieldValue.increment(value),
                  updatedAt: Date.now(),
               },
               { merge: true },
            )
            .then(res => deleteCollection(db, `${docRef}/counts`, 500))
            .catch(err => console.log(err))
      }

      return null
   })

const deleteCollection = (
   db: admin.firestore.Firestore,
   collectionPath: string,
   batchSize: number,
) => {
   const collectionRef = db.collection(collectionPath)
   const query = collectionRef.orderBy('__name__').limit(batchSize)

   return new Promise((resolve, reject) => {
      deleteQueryBatch(db, query, batchSize, resolve, reject)
   })
}

我相信我们迟早会收到COUNT()

【讨论】:

    猜你喜欢
    • 2023-02-25
    • 2020-11-08
    • 1970-01-01
    • 2020-07-29
    • 2017-02-28
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多