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

c2e8gylq  于 2023-03-16  发布在  Java
关注(0)|答案(1)|浏览(114)

我正在使用Google Cloud功能更新“Rooms/{pushId}/ins”,该功能可以从多个“door/{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”节点...
我认为问题可能就在这里,在“更新”常量上,因为每次函数运行时,这个对象都被重新定义为一个整体...
代码继续...

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”被替换为上一次更新的门上的任何数据...我知道update方法应该用于此目的,我想保留这个“更新”对象,以便以后把数据分散到其他路径。2这可能吗?3有什么建议吗?
这是我的数据结构:

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,
      }
    }
  }
e5nszbig

e5nszbig1#

根据我之前对您的相关问题(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节点中添加新的子节点。

相关问题