gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:37:54 24 4
gpt4 key购买 nike

我正在使用 Google Cloud 函数更新“Rooms/{pushId}/ins”,该函数从多个“doors/{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”常量上,因为每次函数运行时都会将此对象作为一个整体重新定义...

代码继续...

        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 数据,每次我更新一个“Door/{MACaddress/Ins”时,整个“Rooms/{pushId}/Ins”被替换为上次更新门上的任何数据...我知道 update 方法应该用于此目的,我有点想保留这个“更新”对象以将数据扇出到其他路径稍后。这可能吗?关于如何解决这个问题有什么建议吗?

这是我的数据结构:

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

最佳答案

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

关于javascript - 如何使用更新对象更新节点而不用 Google Cloud Function 覆盖所有子节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50139303/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com