[英]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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.