【问题标题】:How to count documents in cloud firestore?如何计算云 Firestore 中的文档?
【发布时间】:2018-07-17 04:47:58
【问题描述】:

我在使用 Firestore 数据库实现计数器时遇到问题。 我有一个文档集合,其中文档有一个在某个时候更新的字段。

集合 目的 字段:真 目的 字段:假 目的 字段:真

我需要计算值等于 true 的所有字段。该应用同时从多个设备更新。

我怎样才能做到这一点?我需要使用分布式计数器方法吗?仅使用云功能就足够了

【问题讨论】:

    标签: firebase google-cloud-functions google-cloud-firestore


    【解决方案1】:

    Cloud Firestore 限制为每个文档/秒写入一次。我不建议让多个用户同时写入同一个文档。您绝对应该使用Distributed Counters 方法。

    【讨论】:

      【解决方案2】:

      使用云功能。简单的例子:

      // database in the 'posts' collection
        {
          title: "My great post",
          categories: {
          "technology": true,
          "opinion": false,
          "cats": true
        }
      

      云函数脚本:

      const functions = require('firebase-functions');
      const admin = require('firebase-admin');
      admin.initializeApp({
          credential: admin.credential.applicationDefault()
      });
      
      const docRef = admin.firestore().collection('post')
      .where('categories', '==', true)
      .get()
      .then((result) => {
          res.send(result.size());    //return the count
      }).catch(function(error){
          console.log("got an error",error);        
      })
      exports.countFunction = functions.https.onRequest(...);
      

      【讨论】:

        猜你喜欢
        • 2021-05-08
        • 2018-07-10
        • 2018-09-03
        • 2021-04-24
        • 1970-01-01
        • 2018-08-01
        • 2023-03-30
        • 2018-03-28
        • 1970-01-01
        相关资源
        最近更新 更多