使用 Firebase 实时触发器函数中的其他引用值



嗨,我开始使用Firebase函数向我的Android应用程序添加一些后端逻辑,我想使用一些与事件数据值不同的值

exports.makeUppercase = functions.database.ref('path')
     .onWrite(event => {
      const original = event.data.val();
      //I want to use value like this.
      const other_val= root.database.ref('path').val();
      console.log('email', "firms", original);
      const uppercase = original.toUpperCase();
      return event.data.ref.parent.child('uppercase').set(uppercase);
    });

我想使用other_valwith事件数据,但到目前为止我只使用事件数据 ref,但我可以使用更多的父级或子级在数据库 event.data.ref 中升序或降序。我该如何解决?

编辑:我尝试并学习正确的方法来做到这一点,感谢@davidtaubmann的回答。

exports.makeUppercase = functions.database.ref('/nonVerifiedUsers/{email}')
     .onWrite(event => {
      var changed= "";
      // You can use ref parameter like this
      var param=event.params.email;
      admin.database().ref('/uppercase').once('value').then(function(snap){
      changed=snap.val();
          }).then(function(){
              /*if you want to use changed value wait until it return and return where 
              you want using admin.database.ref and use event parameter in reference like 
              this*/
              return admin.database.ref('/path/').child(param).set(changed);
              /*You can return regular event data but make sure you didn't write under 
              same reference server count this again as event and loop until reach 32 th child(maxiumum child nodes)*/
              return event.data.ref.parent.child('uppercase').set(changed);
          });
       //In addition you can return multiple times in one function:
        return event.data.ref.parent.child('dif').set(changed);
      
      });

使用 Firebase-admin node_module

根据我上面的评论,我确实测试了这些选项,并且正如所想的那样,如果您从node_modules初始化Firebase-admin(确保它也包含在packages.json中(,则可以从数据库中检索任何数据。

对于您的代码,我相信您只需在index.js文件的开头添加以下 2 行(以及所有其他初始化(:

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

然后你可以稍后像通常使用 firebase 一样使用该admin,如下所示:

admin.database().ref('users/xxxx').once('value').then(function(snapshot){....

它对我来说非常有效!

最新更新