如何在新的Firebase onUpdate或onWrite触发器中更改值?

时间:2018-09-06 12:27:47

标签: javascript firebase firebase-realtime-database triggers google-cloud-functions

在版本(<= v0.9.1)之前,可以像这样设置数据,现在不再可用...

event.data.ref.child('thisname').set("error");

编辑:这里没有提到二传手!仅如何从onUpdate或onWrite接收值 https://firebase.google.com/docs/functions/beta-v1-diff

解决方案在下面发布

1 个答案:

答案 0 :(得分:1)

Firebase (支持1.0或2.0版)

如果其他人在onUpdate或onWrite触发器中的云函数中更改 / 设置 / 更新时遇到问题,那么这可能会有所帮助你...

首先,这是我的数据树的样子:

"users" : {
    "4h23u45h23509hu346034h5943h5" : {
      "address" : "Backouse 2",
      "city" : "Los Angeles",
      "name" : "Joseph",
       ...
    },
    "23u4g24hg234h2ui342b34hi243n" : {
      "address" : "Streetouse 13",
      "city" : "Los Angeles",
      "name" : "Stefan",
      ...

现在具有云功能:

之前(<= v0.9.1)

exports.updatingUser = functions.database.ref('/users/{pushId}')
.onUpdate(event => {
  var address = event.data.child('address');
  var city = event.data.child('city');

  if (address.changed() || city.changed()) {
      //generateThisname()
      if (thisname == null) {
        event.data.ref.child('name').set("error");     //Important Part
      }
      else {
        event.data.ref.child('name').set(thisname);    //Important Part
      }
      ...

现在(> = v1.0.0)

exports.updatingUser = functions.database.ref('/users/{pushId}')
.onUpdate((change, context) => {
  var addressBefore = change.before.child('address').val();
  var addressAfter = change.after.child('address').val();

  var cityBefore = change.before.child('city').val();
  var cityAfter = change.after.child('city').val();

  //create reference from root to users/{pushId}/
  var rootSnapshot = change.after.ref.parent.child(context.params.pushId)


      if ((addressBefore !== addressAfter) || (cityBefore !== cityAfter)) {
          //generateThisname()
          if (thisname === null) {
              rootSnapshot.child('name').set("error");
          }
          else {   
              rootSnapshot.child('name').set(thisname);
          }
          ...

因此,在设置值之前,首先必须从数据库的根进行引用,然后一直向下到您的值并调用set()