错误" snapshot.val"不是Google Cloud Functions中的功能

时间:2018-05-01 14:46:13

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

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

" ins" node是我将新数据推送到的节点:

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&# 34;不是一个功能 ...

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

1 个答案:

答案 0 :(得分:8)

如果您使用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