Firebase函数从不同路径接收数据和总和 [英] Firebase Function receive data and sum from different path

查看:38
本文介绍了Firebase函数从不同路径接收数据和总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是firebase函数的新手.我想实现一个可以对不同路径的值求和的函数.这是Firebase实时数据库结构.

I'm new in firebase function.I'm want to implement a function that can sum a value from a different path. Here is firebase real-time database structure.

sensor:{
  sensor-1: 1
  sensor-2: 1
  sensor-3: 1
  sensor-4: 1
  sum: 4  
 }

我想要可以将传感器1-4值求和并将其写在"sum:"上的函数js.我的开始

I want function js that can sum sensor 1-4 value and write it on "sum:". that my start

    exports.sumsensor = functions.database.ref('sensor/{id}').onWrite((change)=>{ 
         //compute code in here
         return admin.database().ref('sensor/sum').set('total');
    });

我该如何实现.请帮助我.

how can I implement this. please help me.

推荐答案

您将不得不稍微更改数据库结构:

You will have to change your database structure a bit:

sensor : {
    sensor-1: 1
    sensor-2: 1
    sensor-3: 1
    sensor-4: 1
}

sensorSum : 4

这是云功能代码:

exports.sumsensor = functions.database.ref('sensor/{id}').onWrite((change,context)=>{ 
     let val = +change.after.val()
     //compute code in here
     return admin.database().ref().child('sensorSum').transaction(function(currentTotal) {
         return currentTotal + val;
     });
});

以下是参考链接: firebase交易

这篇关于Firebase函数从不同路径接收数据和总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆