使用firebase函数更改事件时更新值

时间:2017-06-06 10:10:31

标签: android firebase firebase-realtime-database google-cloud-functions

当firebase-functions对“事件”进行任何更改时,我想更新“uniqueCode”值

下面是firebase db的外观

enter image description here

下面是我的代码

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.ok=functions.database.ref("/events/")
.onWrite(event =>{

  var snap = admin.database().ref('uniqueCode');
  snap++;
  admin.database().ref('uniqueCode').set(snap);
});

但如果我在“事件”中更改任何内容,则“uniqueCode”

的值不会改变

最后在@Frank van Puffelen的帮助下,我完成了以下代码

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.ok=functions.database.ref("/events/")
.onWrite(event =>{

admin.database().ref('uniqueCode').once("value", function(snapshot) {
  var value = snapshot.val();
  value++;
  admin.database().ref('uniqueCode').set(value);
  console.log("The read success: " + snapshot.val());
}, function (errorObject) {
  console.log("The read failed: " + errorObject.code);
});

});

0 个答案:

没有答案