【问题标题】:update Value to - updated value in Firestore将值更新为 - Firestore 中的更新值
【发布时间】:2021-08-05 06:18:47
【问题描述】:

我已经构建了一个具有“TotalView”计数功能的 Cloud Firestore 数据库,以显示在我的 Flutter 应用中。

我使用以下(示例)链接从 Firestore 流式传输数据;

FirebaseFirestore.instance.collection('CollectionID').snapshots();

多个用户可以同时查看同一项目,每次用户查看和退出(不是在访问/打开视图时,而是在用户停止查看或移至下一个时更新数据)该项目 - 我想添加(+ 1)实时(最后更新的值) - viewCount 在我的数据库中

liveVideos.doc('docID').update({'viewsCount': viewCount + 1})

我可以通过以下示例方式更新此值;

FirebaseFirestore.instance.collection('CollectionID')
.doc('docID')
.update({'viewCount' : 'initiallyFetchedViewCount' + 1})

上面的代码将 (+1) 添加到最初获取的 viewCount。但如果viewCount 在服务器中已更新(如果该值已增加),那么我想将 (+1) 添加到该增加的值,而不是最初获取的值。

示例统计; 最初获取时的数据

viewCount : 15

用户关闭视图时的数据

viewCount : 33

在这里,我希望服务器将 (+1) 添加到更新值(+133 但不是 15)。

我无法更好或简短地解释它,抱歉冗长的解释。 寻找任何线索或方法来实现这一目标。感谢您在这方面的任何帮助。

【问题讨论】:

    标签: flutter google-cloud-firestore


    【解决方案1】:

    您无需从后端更改它。如果您使用 increment 字段,它会自动将值增加到后端的最新最高数字:

    DocumentReference washingtonRef = db.collection("cities").document("DC");
    
    // Atomically increment the population of the city by 50.
    washingtonRef.update("population", FieldValue.increment(50));
    

    更多关于 here.

    另一种解决方案是使用事务:

    // Create a reference to the document the transaction will use
    DocumentReference documentReference = FirebaseFirestore.instance
      .collection('users')
      .doc(documentId);
    
    return FirebaseFirestore.instance.runTransaction((transaction) async {
      // Get the document
      DocumentSnapshot snapshot = await transaction.get(documentReference);
    
      if (!snapshot.exists) {
        throw Exception("User does not exist!");
      }
    
      // Update the follower count based on the current count
      // Note: this could be done without a transaction
      // by updating the population using FieldValue.increment()
    
      int newFollowerCount = snapshot.data()['followers'] + 1;
    
      // Perform an update on the document
      transaction.update(documentReference, {'followers': newFollowerCount});
    
      // Return the new count
      return newFollowerCount;
    })
    .then((value) => print("Follower count updated to $value"))
    .catchError((error) => print("Failed to update user followers: $error"));
    
    

    更多关于 here.

    重要的是要知道,对于这两种情况,您都需要有一个有效的互联网连接。通常没有它,firestore 也可以工作。

    【讨论】:

    • FieldValue.increment(1) 解决了我的问题。 @TarikHuber 感谢您的及时响应(加)完美的解决方案。你太棒了!
    猜你喜欢
    • 2023-03-23
    • 2021-08-29
    • 2019-09-30
    • 2021-12-02
    • 1970-01-01
    • 2022-01-08
    • 2021-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多