【问题标题】:Firebase function .onWrite not working?Firebase 函数 .onWrite 不起作用?
【发布时间】:2018-05-04 07:14:26
【问题描述】:

好的,我查看了类似的问题,例如 Firebase function onWrite not being called,并认为获得参考是我的错,但我不知道我的 Firebase 函数发生了什么。

我只是想在对数据库进行写入时获取一个写入我的数据库的函数。我完全按照 firebase 教程进行操作:

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

// The Firebase Admin SDK to access the Firebase Realtime Database.
//https://firebase.google.com/docs/functions/database-events

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

// const gl = require('getlocation');

exports.helloWorld = functions.https.onRequest((request, response) => {
 response.send("Hello from Firebase!");
});

exports.enterLocation = functions.database.ref('/Users/{name}') //brackets is client param
    .onWrite(event => {
      // Grab the current value of what was written to the Realtime Database.
      // const original = event.data.val();
      console.log('SKYLAR HERE:', event.params.name);
      // You must return a Promise when performing asynchronous tasks inside a Functions such as

      return firebase.database().ref('/Users/{name}').set({ location: 'test loc' });
  });

该函数正在运行,但在我的日志中我收到一个非常无用的错误,它正在获取 {name} 参数,并且数据肯定已写入我的数据库,但是我的 SERVER 代码没有写入:

我明白了——

ReferenceError:firebase 未定义在 export.enterLocation.functions.database.ref

按照定义,这是没有意义的。我只想在我创建的用户下添加一个额外的孩子,就像我已经使用“密码”一样

我做错了什么?

【问题讨论】:

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


    【解决方案1】:

    而不是这个:

     return firebase.database().ref('/Users/{name}').set({ location: 'test loc' });
    

    使用这个:

     return admin.database().ref('/Users/{name}').set({ location: 'test loc' });
    

    【讨论】:

      【解决方案2】:

      这里有两个问题。首先,您没有在代码中的任何地方定义firebase。我认为您的意思是使用 admin 而不是使用 Admin SDK。

      其次,您似乎正在尝试将变量插值到字符串中以构建 ref 的名称。你的语法在这里是错误的。

      我想你是想在最后一行代码中这样说:

      return admin.database().ref(`/Users/${name}`).set({ location: 'test loc' });
      

      注意字符串引号上的反引号。该 JavaScript 语法允许您使用 ${exp} 在字符串中插入某些表达式的内容。

      事实证明,您甚至不需要在这里使用管理 SDK。由于您试图写回触发该函数的同一位置,因此您可以只使用来自事件对象的 ref:

      return event.data.adminRef.set({ location: 'test loc' });
      

      【讨论】:

      猜你喜欢
      • 2018-03-28
      • 2017-08-02
      • 1970-01-01
      • 2021-12-17
      • 2019-01-31
      • 2019-08-10
      • 1970-01-01
      • 1970-01-01
      • 2018-10-11
      相关资源
      最近更新 更多