通过QuerySnapshot的size属性,可以得到一个集合的文档数,如下:
db.collection("comments").get().then(function(querySnapshot) {
console.log(querySnapshot.size);
});
但是,您应该注意,这意味着您每次都阅读了集合中的所有文档,您想要获取文档的数量,因此它有成本。
因此,如果您的集合有很多文档,更实惠的方法是维护一组包含文档数量的 distributed counters。每次添加/删除文档时,都会增加/减少计数器。
基于documentation,以下是写操作的方法:
首先,初始化计数器:
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)
最后,看文档如何查询计数器值!