【问题标题】:Error "snapshot.val" is not a function in Google Cloud Functions错误“snapshot.val”不是 Google Cloud Functions 中的函数
【发布时间】:2018-10-11 14:48:13
【问题描述】:

创建新节点时,我想创建相同的数据并将其推送到不同的节点。

“ins”节点是我将新数据推送到的节点:

root: { 
  doors: {
    111111111111: {
       MACaddress: "111111111111",
       inRoom: "-LBMH_8KHf_N9CvLqhzU",
       ins: {
          // I am creating several "key: pair"s here, something like:
          1525104151100: true,
          1525104151183: true,
       }
    }
  },
  rooms: {
    -LBMH_8KHf_N9CvLqhzU: {
      ins: {
        // I want it to clone the same data here:
        1525104151100: true,
        1525104151183: true,
      }
    }
  }

我的功能代码如下,但它根本不起作用。当我使用 onCreate 触发器(这就是我所需要的)时,我什至无法启动该功能。关于如何完成这项工作的任何想法?

exports.updateRoom = functions.database.ref('doors/{MACaddress}/ins')
.onCreate((snapshot, context) => {
    const timestamp = snapshot.val();
    const roomPushKey = functions.database.ref('doors/{MACaddress}/inRoom');
    console.log(roomPushKey);  
    return snapshot.ref.parent.parent.child('rooms').child(roomPushKey).child('ins').set(timestamp);
});  

注意:我修改了代码并通过将触发器更改为 onWrite 来运行它,但是像这样我收到一条错误消息:"snapshot.val" is not a函数...

exports.updateRoom = functions.database.ref('doors/{MACaddress}/ins').onWrite((snapshot, context) => {     
    const timestamp = snapshot.val();
    const roomPushKey = functions.database.ref('doors/{MACaddress}/inRoom');
    console.log(roomPushKey);
    return snapshot.ref.parent.parent.child('rooms').child(roomPushKey).child('ins').set(timestamp);
});  

【问题讨论】:

  • 我做到了。我会将其标记为正确,但我的代码仍然无法正常工作。你能指出我正确地编写函数吗?我会提出一个新问题。
  • 它仍然不能与onCreate 一起工作吗?我在下面解释了为什么它不适用于onWrite
  • 是的...onCreate 没有运行...我已经设法根据您关于onWrite 的提示取得了一些进展。但我希望能得到更多帮助:stackoverflow.com/questions/50120415/…

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


【解决方案1】:

如果您使用onWrite,您必须执行以下操作:

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
});

onWrite 在指定路径发生任何更改时使用,因此您可以检索before 更改和after 更改。

更多信息在这里:

https://firebase.google.com/docs/functions/beta-v1-diff#realtime-database

https://firebase.google.com/docs/reference/functions/functions.Change

onCreate,你可以这样做:

exports.dbCreate = functions.database.ref('/path').onCreate((snap, context) => {
const createdData = snap.val(); // data that was created
});

因为onCreate 在您向数据库添加新数据时触发。

【讨论】:

    猜你喜欢
    • 2018-10-11
    • 2021-05-08
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    相关资源
    最近更新 更多