我想获取 firestore 集合中的文档总数,我正在制作一个论坛应用程序,所以我想在每个讨论中显示当前的评论数量。有没有类似的db.collection("comments").get().lenght
东西?
通过 的size
属性QuerySnapshot
,可以得到一个集合的文档数,如下:
db.collection("comments").get().then(function(querySnapshot) {
console.log(querySnapshot.size);
});
但是,您应该注意,这意味着每次想要获取文档数量时都需要阅读集合的所有文档,因此,它是有成本的。
因此,如果您的集合中有大量文档,则更实惠的方法是维护一组保存文档数量的分布式计数器。每次添加/删除文档时,都会增加/减少计数器。
根据文档,这里是写操作的方法:
首先,初始化计数器:
const db = firebase.firestore();
function createCounter(ref, num_shards) {
let batch = db.batch();
// Initialize the counter document
batch.set(ref, { num_shards: num_shards });
// Initialize each shard with count=0
for (let i = 0; i < num_shards; i++) {
let shardRef = ref.collection('shards').doc(i.toString());
batch.set(shardRef, { count: 0 });
}
// Commit the write batch
return batch.commit();
}
const num_shards = 3; //For example, we take 3
const ref = db.collection('commentCounters').doc('c'); //For example
createCounter(ref, num_shards);
然后,当你写评论时,使用如下批量写入:
const num_shards = 3;
const ref = db.collection('commentCounters').doc('c');
let batch = db.batch();
const shard_id = Math.floor(Math.random() * num_shards).toString();
const shard_ref = ref.collection('shards').doc(shard_id);
const commentRef = db.collection('comments').doc('comment');
batch.set(commentRef, { title: 'Comment title' });
batch.update(shard_ref, {
count: firebase.firestore.FieldValue.increment(1),
});
batch.commit();
对于文档删除,您可以使用以下方法减少计数器: firebase.firestore.FieldValue.increment(-1)
最后,在文档中查看如何查询计数器值!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句