我考虑了两种可能的方法。
1.直接统计集合的文档
您可以使用QuerySnapshot 的size 属性,就像
admin.firestore().collection('groups/{groupId}/members/{memberId}')
.get()
.then(querySnapshot => {
console.log(querySnapshot.size);
//....
return null;
});
这里的主要问题是成本,如果子集合包含大量文档:通过执行此查询,您将为每个文档收取一次阅读费用的子集合。
2。另一种方法是为每个子集合维护一些计数器
您将编写两个云函数,基于分布式计数器,如以下 Firebase 文档项中所述:https://firebase.google.com/docs/firestore/solutions/counters。我们在下面的例子中使用了 3 个分片。
首先,当将新文档添加到 subCollec 子集合时,云函数会增加计数器:
//....
const num_shards = 3;
//....
exports.incrementSubCollecCounter = functions
.firestore.document('groups/{groupId}/members/{memberId}')
.onCreate((snap, context) => {
const groupId = context.params.groupId;
const shard_id = Math.floor(Math.random() * num_shards).toString();
const shard_ref = admin
.firestore()
.collection('shards' + groupId)
.doc(shard_id);
if (!snap.data().counterIncremented) {
return admin.firestore().runTransaction(t => {
return t
.get(shard_ref)
.then(doc => {
if (!doc.exists) {
throw new Error(
'Shard doc #' +
shard_id +
' does not exist.'
);
} else {
const new_count = doc.data().count + 1;
return t.update(shard_ref, { count: new_count });
}
})
.then(() => {
return t.update(snap.ref, {
counterIncremented: true //This is important to have the Function idempotent, see https://cloud.google.com/functions/docs/bestpractices/tips#write_idempotent_functions
});
});
});
} else {
console.log('counterIncremented NOT NULL');
return null;
}
});
然后,当从 subCollec 子集合中删除文档时,第二个 Cloud Function 会减少计数器:
exports.decrementSubCollecCounter = functions
.firestore.document('groups/{groupId}/members/{memberId}')
.onDelete((snap, context) => {
const groupId = context.params.groupId;
const shard_id = Math.floor(Math.random() * num_shards).toString();
const shard_ref = admin
.firestore()
.collection('shards' + groupId)
.doc(shard_id);
return admin.firestore().runTransaction(t => {
return t.get(shard_ref).then(doc => {
if (!doc.exists) {
throw new Error(
'Shard doc #' +
shard_id +
' does not exist.'
);
} else {
const new_count = doc.data().count - 1;
return t.update(shard_ref, { count: new_count });
}
});
});
});
这里,相比方案1,由于我们有3个分片,当你想知道subCollec子集合中的文档数时,你只需要读取3个文档。
有关如何初始化分布式计数器的详细信息,请查看文档。您必须为每个groupId 集合初始化一次(即admin.firestore().collection('shards' + groupId))