如何从另一个节点事件触发的`onWrite`函数中访问Google Cloud Function中的特定节点?

时间:2022-12-24 16:01:43

When creating a new node, I want to create and push that same data into a different node.

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

The Door/111111111111/ins node is the node I am pushing the new data into:

Door / 111111111111 / 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 the function to clone the same data here:
        1525104151100: true,
        1525104151183: true,
      }
    }
  }

This is my function which is throwing an error:

这是我的函数,它抛出一个错误:

TypeError: change.before.ref.parent.child(...).val is not a function

TypeError:change.before.ref.parent.child(...)。val不是函数

Code:

码:

exports.updateRoom = functions.database.ref('/doors/{MACaddress}/ins').onWrite((change, context) => {
    const beforeData = change.before.val(); // data before the write
    console.log(beforeData); // all good so far
    const afterData = change.after.val(); // data after the write
    console.log(afterData); // all good so far

    const roomPushKey = change.before.ref.parent.child('/inRoom').val(); // ERROR
    console.log(roomPushKey);

    return change.after.ref.parent.parent.parent.child('/rooms').child(roomPushKey).child('/ins').set(afterData);
});

What is wrong with my path? How can I get it to update the other node?

我的路有什么问题?如何让它更新其他节点?

1 个解决方案

#1


2  

child() is a method on Reference that returns another Reference object. Reference doesn't have a val() method because it doesn't contain any data. It's just a reference.

child()是Reference上的一个方法,它返回另一个Reference对象。引用没有val()方法,因为它不包含任何数据。这只是一个参考。

To get data outside the location of the database trigger, you need to query Realtime Database for it. Use the once() method for that. This is extremely common, and you should be able to use samples and documentation to figure out what you need to do.

要获取数据库触发器位置之外的数据,您需要为其查询实时数据库。使用once()方法。这是非常常见的,您应该能够使用示例和文档来确定您需要做什么。

#1


2  

child() is a method on Reference that returns another Reference object. Reference doesn't have a val() method because it doesn't contain any data. It's just a reference.

child()是Reference上的一个方法,它返回另一个Reference对象。引用没有val()方法,因为它不包含任何数据。这只是一个参考。

To get data outside the location of the database trigger, you need to query Realtime Database for it. Use the once() method for that. This is extremely common, and you should be able to use samples and documentation to figure out what you need to do.

要获取数据库触发器位置之外的数据,您需要为其查询实时数据库。使用once()方法。这是非常常见的,您应该能够使用示例和文档来确定您需要做什么。