Skip to content Skip to sidebar Skip to footer

How To Query The Existing Children Of A Sibling Node And Loop Over Them To Detect If It Exists?

I am trying to update (adding) new children on a firebase database. On this scenario I am updating two nodes and_'door/{MACaddress_1}/ins'_ & _'doors/{MACaddress_2}/ins'_ and b

Solution 1:

This question originated two different approaches. Please find them here:

1) By Renaud Tarnec using the Cloud Function

This should work, but I haven't test it. You may need to test is insBefore is undefined in addition to testing it is null. I let you fine tune it.

let insAfter;
let roomPushKey ;
exports.updateRoomIns = functions.database.ref('/doors/{MACaddress}').onWrite((change, context) => {
    const afterData = change.after.val(); // data after the write
    roomPushKey = afterData.inRoom;
    insAfter = afterData.ins;
    return admin.database().ref('/rooms/' + roomPushKey).once('value').then(snapshot => {
    const insBefore = snapshot.val().ins;
    const updates = {};
    if (insBefore === null || insBefore === undefined ) {
        Object.keys(insAfter).forEach(key => {
           updates['/rooms/' + roomPushKey + '/ins/' + key] = true;
        });
    } else {
        Object.keys(insAfter).forEach(key => {
           if (insBefore.hasOwnProperty(key)) {
              updates['/rooms/' + roomPushKey + '/ins/' + key + '_a'] = true; 
           } else {
              updates['/rooms/' + roomPushKey + '/ins/' + key] = true;
           }
        });
    }
    return admin.database().ref().update(updates);
    });
});.catch(error => {
    console.log(error);
    //+ other error treatment if necessary

});

2) the second approach was a more direct one

I have decided to solve it on the Arduino program, because all doors have different MAC Addresses I simply added the MAC address to the end of of the timestamp and because no door will register two ins at the same time that did the trick for me.


Post a Comment for "How To Query The Existing Children Of A Sibling Node And Loop Over Them To Detect If It Exists?"