【问题标题】:Firebase snapshot.val() is not a functionFirebase snapshot.val() 不是函数
【发布时间】:2020-07-01 23:07:05
【问题描述】:

我写了这个方法,它应该控制台记录触发的节点数据,但我得到了错误。

这是我试过的”

exports.makeUppercase = functions.database
  .ref('/users/{userId}/matches')
  .onWrite((snapshot, context) => {
    // Grab the current value of what was written to the Realtime Database.
    //const original = snapshot.val();
    console.log('OnWrite works' + snapshot.after.val());
    // const uppercase = original.toUpperCase();
    // You must return a Promise when performing asynchronous tasks inside a Functions such as
    // writing to the Firebase Realtime Database.
    // Setting an "uppercase" sibling in the Realtime Database returns a Promise.
    return null;
  });

这是错误: make大写 TypeError:snapshot.val 不是位于 cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions) 的 export.makeUppercase.functions.database.ref.onWrite (/srv/index.js:49:44) 的函数.js:131:23) at /worker/worker.js:825:24 at at process._tickDomainCallback (internal/process/next_tick.js:229:7)

我是不是做错了什么?

【问题讨论】:

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


    【解决方案1】:

    来自docs

    事件数据现在是 DataSnapshot。

    在早期版本中,event.data 是一个 DeltaSnapshot;从 v 1.0 开始,它是一个 DataSnapshot。

    对于 onWrite 和 onUpdate 事件,data 参数有 before 和 after 字段。其中每一个都是一个 DataSnapshot,其方法与 admin.database.DataSnapshot 中可用的方法相同。

    例如:

    exports.dbWrite = functions.database.ref('/path').onWrite((change, context) => {
      const beforeData = change.before.val(); // data before the write
      const afterData = change.after.val(); // data after the write
    });
    

    因此,在您的代码中,您需要使用after 属性在写入后检索或使用before 属性:

    const original = snapshot.after.val();
    

    【讨论】:

    • 谢谢,看来问题是我首先需要将它添加到变量,然后控制台记录它。
    猜你喜欢
    • 1970-01-01
    • 2018-10-11
    • 2018-10-11
    • 2020-01-26
    • 1970-01-01
    • 1970-01-01
    • 2016-11-13
    • 2019-02-03
    相关资源
    最近更新 更多