繁体   English   中英

Flutter firestore 获取值的总和

[英]Flutter firestore get sum of values

我是 flutter 和 Firestore 开发的新手。

我有一个帖子集合。 对于每个帖子,我都有反馈的子集。 反馈可以是好的也可以是坏的。 我想要做的是得到好的和坏的反馈的总和。

在这里,我展示了我所有的帖子,其中包含好的和坏的反馈计数。

我可以在每个帖子中获取帖子和反馈。 但我不知道如何在帖子中添加反馈。 或者计算总和。

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) 并计算总和可能是“代价高昂的”——无论是在性能还是金钱方面,因为 Firestore 的收费是基于读取、写入、删除操作的数量。 现在,如果您有 1000 个文档和 100 个移动应用程序用户,那么每天的读取操作数将是 1000 x 100 = 100,000。 每增加一个文档,阅读计数将增加 100。

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

goodCount:40
badCount:11

查看Firestore 文档或快速教程以了解如何操作。

** 感谢 Frank 提供的文档链接。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM