【问题标题】:Cloud Function to Update a Record (value = value + newValue) whenever a value chages in Firebase Databse每当 Firebase 数据库中的值发生变化时更新记录的云函数(值 = 值 + 新值)
【发布时间】:2021-01-29 09:48:15
【问题描述】:

我是 Cloud Functions 新手。

我有一个“驱动程序”表,但细节很少。

现在我想编写一个 Firebase 云函数,它将

  1. 只要设置了“drivers/{driverId}/history/{rideId}/rating”中的值就会触发。
  2. 将 totalRating (drivers/{driverId}/totalRating) 值更新为 oldTotalRatingValue + NewTotalRatingValue。

任何帮助或参考将不胜感激。

提前致谢。

=============我的方法======================

exports.increaseRating = functions.database.ref('/drivers/{driverId}/history/{historyId}/rating')
.onUpdate((snapshot, context) => {
    var newRating = snapshot.after.val();
    var oldRating = 0;
    var db = admin.database();
    var ref = db.ref(`/drivers/${context.params.driverId}/totalRating`);
    ref.once("value", function(snapshot) {
      oldRating = snapshot.val();
    });
    console.log(oldRating);
    var finalRating = oldRating + newRating;
    return admin.database().ref(`/drivers/${context.params.driverId}`).update({
        "totalRating": finalRating,
    })
})

但我的 var oldRating 不会更新到数据库值。

【问题讨论】:

  • 与特定问题无关,但您可能需要阅读有关数据结构的 Firebase 文档,因为它针对您拥有的数据嵌套类型提出了建议:firebase.google.com/docs/database/web/…
  • 如果目标是观察所有驱动程序的历史变化,这不是正确的结构。您应该打破每个驱动程序的历史并将其存储在更高级别并观察其变化.

标签: javascript node.js firebase firebase-realtime-database google-cloud-functions


【解决方案1】:

如果要更新totalRanking,则需要使用Transaction,以避免在当前云成功写入新值之前,云函数的另一个实例写入totalRanking位置功能。

以下应该可以工作(未经测试):

exports.increaseRating = functions.database.ref('/drivers/{driverId}/history/{historyId}/rating')
    .onUpdate((snapshot, context) => {

        const newRating = snapshot.after.val();

        const totalRatingRef = admin.database().ref(`/drivers/${context.params.driverId}/totalRating`);

        return totalRatingRef.transaction(currentTotalRating => {
            // If /drivers/{driverId}/history/{historyId}/rating has never been set, newRating will be `null`.
            return currentTotalRating + newRating;
        });

    });

请注意,我们正在返回 Transaction 返回的 Promise。关于这个关键点的更多细节在doc

【讨论】:

    【解决方案2】:

    您必须使用实时数据库触发器onWrite 编写云函数。这是documentation。方法documentation 说:

    每次 Firebase 实时数据库写入时触发的事件处理程序 发生任何类型的(创建、更新或删除)。

    函数的开头应该或多或少像:

    ...
    exports.<your function name> = 
        functions.database.ref('drivers/{driverId}/history/{rideId}/rating')
        .onWrite((snapshot, context) => {
    ...
    

    说到更新你的云功能是节点应用程序,所以你可以在其中使用 firebase admin sdk。教程是here。获取价值并更新。

    我知道您需要driverId 以供参考。您可以像这样context.params.driverId 从触发器通配符中获取它(检查通配符是否在触发器文档中)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-04
      • 1970-01-01
      • 2020-12-27
      • 2017-05-18
      • 1970-01-01
      • 1970-01-01
      • 2019-07-03
      相关资源
      最近更新 更多