如何使用更新对象更新节点而不使用Google Cloud Function覆盖所有子节点?

时间:2018-05-02 16:22:42

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

我正在更新" Rooms / {pushId} / ins"使用Google Cloud功能从多个"门/ {MACaddress} / ins"中获取新的 In 数据。 该功能目前如下:

exports.updateRoomIns = functions.database.ref('/doors/{MACaddress}').onWrite((change, context) => {
    const beforeData = change.before.val(); // data before the write (data of all the doors child nodes)
    const afterData = change.after.val(); // data after the write (data of all the doors child nodes)
    const roomPushKey = afterData.inRoom; // get the right room
    const insbefore = beforeData.ins;
    const insafter = afterData.ins; // get the after data of only the "ins" node
    console.log(insafter);

    if (insbefore != insafter) {
        const updates = {}; 

" const updates = {}"创建一个空的对象(稍后)填充,并(稍后)更新" rooms / {roompushkey} / ins"节点...

我认为这个问题可能出现在"更新" const,因为每次函数运行时都会将此对象重新定义为整体...

代码继续......

        updates['/rooms/' + roomPushKey + '/ins'] = insafter; // populate the "INS" object with the values taken from the "/doors/{MACaddress/ins"
        return admin.database().ref().update(updates); // do the update
    } else {
    return
    }
});

如果我只有一扇门,这将有效,但由于我有几个门有不同的Ins数据,每次我更新一个"门/ {MACaddress / Ins",整个"房间/ {pushId} / INS"取代上次更新门上的任何数据...我知道更新方法应该用于此目的,我有点想保留这个"更新"对象以后将数据扇出到其他路径。这可能吗?关于如何解决这个问题的任何建议?

这是我的数据结构:

root: { 
  doors: {
    111111111111: {
       MACaddress: "111111111111",
       inRoom: "-LBMH_8KHf_N9CvLqhzU", // I will need this value for the clone's path
       ins: {
          // I am creating several "key: pair"s here, something like:
          1525104151100: true,
          1525104151183: true,
       }
    },
    222222222222: {
       MACaddress: "222222222222",
       inRoom: "-LBMH_8KHf_N9CvLqhzU", // I will need this value for the clone's path
       ins: {
          // I am creating several "key: pair"s here, something like:
          2525104157710: true,
          2525104157711: true,
       }
    }
  },
  rooms: {
    -LBMH_8KHf_N9CvLqhzU: {
      ins: {
        // I want the function to clone the same data here:
        1525104151100: true,
        1525104151183: true,
      }
    }
  }

1 个答案:

答案 0 :(得分:2)

根据我之前对相关问题(How to clone a node to another path based on a reference value from the initial path on Google Cloud Functions?)的回答,我将调整代码如下:

exports.updateRoom = functions.database.ref('/doors/{MACaddress}').onWrite((change, context) => {
    const afterData = change.after.val(); // data after the write

    const roomPushKey = afterData.inRoom;
    const ins = afterData.ins;

    const updates = {};

    Object.keys(ins).forEach(key => {
        updates['/rooms/' + roomPushKey + '/ins/' + key] = true;
    });

    return admin.database().ref().update(updates);

}).catch(error => {
    console.log(error);
    //+ other rerror treatment if necessary

});

换句话说,不是替换完整的ins对象,而是在现有的ins节点中添加新的子节点。