在订阅集合时,遍历每个文档的集合项和sum属性



我有一个集合counters,每个counter文档都有一个集actions。每个action都有一个step属性,它是一个数字。

以下是我如何获得所有(订阅(counters

firestoreRef.onSnapshot(
(countersSnapshot) => {
const arrayOfCounters = [];
if (!countersSnapshot.empty) {
countersSnapshot.forEach((counterDocument) =>
arrayOfCounters.push(counterDocument),
);
}
setCounters(arrayOfCounters); // <- this is React.useState()[1]
},
(e) => console.error(e),
);

我曾经在CCD_ 8中使用CCD_;CCD_ 9";(它是actions中所有step值的总和(如下:

const getCurrentValue = (initialValue, actions, step) => {
if (!actions.length) {
return initialValue;
}
return actions.reduce((a, b) => {
return b.type === TYPE_INCREMENT ? a + step : a - step;
}, initialValue);
};

然而,我决定将actions转换为Firestore集合。我应该如何获得所有计数器及其当前值,同时订阅这些计数器,以便获得实时更新?

以社区Wiki的形式发布基于评论的答案。

下面的例子,应该提供一个很好的理解和帮助解决问题的想法。例如,订阅每个counter.ref.collection('actions')可能是一个解决方案,但是,考虑到将对每个文档进行的所有查询。我相信这个链接应该会有所帮助,因为它是类似的情况,并提供了多种解决方案的替代方案(包括代码示例(。

最新更新