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

Joa*_*cho 3 javascript database firebase firebase-realtime-database google-cloud-functions

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

"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,
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

我的功能代码如下,但它根本不起作用.当我使用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);
});  
Run Code Online (Sandbox Code Playgroud)

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

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);
});  
Run Code Online (Sandbox Code Playgroud)

Pet*_*dad 11

如果您正在使用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
});
Run Code Online (Sandbox Code Playgroud)

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
});
Run Code Online (Sandbox Code Playgroud)

自从onCreate向数据库添加新数据时触发.