随着size https://firebase.google.com/docs/reference/js/firebase.firestore.QuerySnapshot#size的财产QuerySnapshot https://firebase.google.com/docs/reference/js/firebase.firestore.QuerySnapshot,可以得到一个集合的文档数量,如下:
db.collection("comments").get().then(function(querySnapshot) {
console.log(querySnapshot.size);
});
HOWEVER,您应该注意,这意味着您阅读了该集合的所有文档每一次您想要获得文档的数量,因此它是有成本的。
因此,如果您的收藏有大量文档,更经济的方法是维护一组文档分布式计数器 https://firebase.google.com/docs/firestore/solutions/counters保存文档的数量。每次添加/删除文档时,都会增加/减少计数器。
基于文档 https://firebase.google.com/docs/firestore/solutions/counters,这里是如何进行写入:
首先,初始化计数器:
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)
最后,请参阅文档如何查询计数器值!