【问题标题】:Getting snapshot size of cloud firestore collection in web javascript [duplicate]在 Web javascript 中获取云 Firestore 集合的快照大小 [重复]
【发布时间】:2020-11-24 09:52:11
【问题描述】:

我正在开发一个使用 javascript 的 Web 应用程序,使用云 Firestore 作为数据库。在我的数据库中,我的集合中有大约 400 000 个文档。当我编写查询以获取快照大小时,我的网站将进入调试状态并且永远不会返回大小。

db2.collection("Products").get().then(function(querySnapshot) {
   querySnapshot.forEach(function(doc) {
      // console.log(doc.id, " => ", doc.data());
   });
   console.log("size",querySnapshot.size);
})
.catch(function(error) {
   console.log("Error getting documents: ", error);
});

因此,我编写了另一个替代查询,如下所示,使用带有查询游标的分页数据。

var productfirst = db2.collection("Products").orderBy("ProductName").limit(10000);

getProducts(productfirst);
    
function getProducts(first){
    
   first.get().then(function (documentSnapshots) {
       // Get the last visible document
       pcount = pcount + documentSnapshots.size;
       console.log("products",documentSnapshots.size,pcount);
       var lastVisible = documentSnapshots.docs[documentSnapshots.docs.length-1];
    
       document.getElementById('totalProducts').textContent = pcount;
    
       if(documentSnapshots.size == 0){
           document.getElementById('totalProducts').textContent = pcount;
           // document.getElementById("loadspinner").style.display = "none";
       }
       else {
           // Construct a new query starting at this document, get the next 25 cities.
           var next = db2.collection("Products").orderBy("ProductName").startAfter(lastVisible)
                      .limit(10000);
    
           getProducts(next);
       }
    });
}

此查询返回快照大小,但获取总计数需要 5 分钟以上。还有其他更快的方法来获取 Firestore 集合大小吗?而且,我需要将这些文档设置到数据表中。

【问题讨论】:

标签: javascript html firebase google-cloud-firestore datatables


【解决方案1】:

由于 Firebase Cloud Firestore 根据文档读取向您收费,这将使您的账单达到天文数字。我建议您创建一个文档来存储这些统计信息。可以使用fieldvalue 功能与 onCreate 和 onDelete 的database triggers 配对来完成。

这里是上述云功能的实现参考

// IMPORT
const functions = require('firebase-functions');
const admin = require('firebase-admin');

// INIT
const firebaseApp = admin.initializeApp(yourConfig)
var db = firebaseApp.firestore();
var fieldVal = admin.firestore.FieldValue;


// INCREMENT UPON CREATION
exports.makeUppercase = functions.firestore.document("/Products/{productID}").onCreate((handler, context)=>{
    db.collection("statistics").doc("products").update({
        nProducts: fieldVal.increment(1)
    })
})

// DECREMENT UPON DELETION
exports.makeUppercase = functions.firestore.document("/Products/{productID}").onDelete((handler, context)=>{
    db.collection("statistics").doc("products").update({
        nProducts: fieldVal.increment(-1)
    })
})

或者,您也可以在产品管理面板上使用上述增量和减量功能来摆脱对云功能的需求。只需确保您事先已创建统计文档即可。

【讨论】:

  • 我们需要存储总数吗?有没有其他方法可以一次获取集合大小而不是读取所有文档。
猜你喜欢
  • 2019-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-13
  • 2021-03-04
  • 2018-03-18
  • 2020-11-27
  • 1970-01-01
相关资源
最近更新 更多