Flutter firestore 获取值的总和

Flutter firestore get sum of values

我是 flutter 和 firestore 开发的新手。

我有 collection 个 post。对于每个 post 我有 sub-collection 的反馈。 反馈可以是好的也可以是坏的。 我想做的是得到好的和坏的反馈的总和。

在这里,我显示了我所有的 post 以及好的和坏的反馈计数。

我可以得到 posts 和他们每个人的反馈。 但我不知道如何向 posts 添加反馈。或者计算总和。

Stream<List<Post>> get myPosts {
Query query = Firestore.instance
    .collection('posts')
    .where("userId", isEqualTo: uid)
    .orderBy('modifiedDate', descending: true);

final Stream<QuerySnapshot> snapshots = query.snapshots();

return snapshots.map((QuerySnapshot snapshot) {
  List<Post> postList = snapshot.documents.map((doc) {
    Firestore.instance
        .collection('posts')
        .document(doc.documentID)
        .collection('feedback')
        .getDocuments()
        .then((allFeedbackDocs) => {
              allFeedbackDocs.documents.forEach((feedbackDoc) {
                var feedData = feedbackDoc.data;
              })
            });

    return Post.fromMap(doc.data, doc.documentID);
  }).toList();

  return postList;
});
  }

理想情况下,我想做的是向“Post.fromMap”提供好的和坏的反馈计数“

有人可以提供一些帮助吗?

基于@Sukhi 的回答尝试了这个,但出现错误。 一直收不到数据,即使有文档

如果我理解正确,如果没有“feedbackCount”文档,我必须添加它。如果有,我必须更新计数。

var feedBackRef = Firestore.instance
            .collection('posts')
            .document('fiCv95srzMufldYb15zw')
            .collection('feedbackCount')
            .document();

        Firestore.instance.runTransaction((transaction) async {
          transaction.get(countryRef).then((result) => {
                if (result.exists)
                  {print('has data')}
                else
                  {print('no data')}
              });
        });

在@Sukhi 的帮助下。 我想到了这个;

  Future<void> updateFeedbackCount(
      DocumentReference feedbackRef, int good, int bad, String docId) async {
    var postRef =
        Firestore.instance.collection(APIPath.posts()).document(docId);

    await Firestore.instance.runTransaction((transaction) async {
      await transaction.get(postRef).then((res) async {
        if (!res.exists) {
          throw PlatformException(
            code: 'POST_FOR_FEEDBACK_NOT_FOUND',
            message: "Could not found post for the feedback.",
          );
        }
        
        var goodCount = res.data['good'] + good;
        var badCount = res.data['bad'] + bad;
        
        transaction.update(postRef, {
          'good': goodCount,
          'bad': badCount,
        });
      });
    });
  }

  @override
  Future<void> addFeedback(UserFeedback feedback, String postId) async {
    var postRef =
        Firestore.instance.collection(APIPath.feedback(postId)).document();

    await postRef.setData(feedback.toMap()).then((result) =>
        updateFeedbackCount(postRef, feedback.good, feedback.bad, postId));
  }

聚合所有文档 (.forEach) 并计算总和可能 'costly' - 在性能和金钱方面都是如此,因为 Firestore 收费是基于读取、写入、删除操作的数量。 现在,如果您有 1000 个文档和 100 个移动应用程序用户,那么每天的读取操作数将为 1000 x 100 = 100,000。每增加一个文档,阅读次数将增加 100。

处理它的一种方法是用计数维护另一个文档。因此,文档将只包含两个计数

goodCount:40
badCount:11

查看 this Firestore documentation or this 快速教程了解如何操作。

** 感谢 Frank 提供的文档 link。