How to clone a node to another path based on a reference value from the initial path on Google Cloud Functions?

后端 未结 1 875
悲哀的现实
悲哀的现实 2021-01-23 07:08

I am trying clone an \"original\" node\'s data (as soon as I create the data) to a path that is based on the original node\'s path.

This is my data structure:



        
相关标签:
1条回答
  • 2021-01-23 07:26

    The following should work.

    const admin = require("firebase-admin");
    ....
    ....
    
    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 = {};
        updates['/rooms/' + roomPushKey] = ins;
        return admin.database().ref().update(updates);
    
    }).catch(error => {
        console.log(error);
        //+ other rerror treatment if necessary
    
    });
    

    Here are some explanations:

    You get the roomPushKey by reading the "data after the write" as an object: roomPushKey = afterData.inRoom. You don't need to do roomPushKey.once('child_added').then()

    Once you have the roomPushKey, you create a new child node in the rooms node by using update() and creating an object with square brackets notation which allow you to assign the id of the node (i.e. roomPushKey).

    Note that you could also do:

    return admin.database().ref('/rooms/' + roomPushKey).set(ins);
    

    Note also that you have to import firebase-admin in order to be able to do return admin.database().ref()...

    Finally, I would suggest that you have a look at the three following videos from the Firebase team: youtube.com/watch?v=7IkUgCLr5oA&t=517s & youtube.com/watch?v=652XeeKNHSk&t=27s & youtube.com/watch?v=d9GrysWH1Lc. A must for anyone starting coding for Cloud Functions.

    0 讨论(0)
提交回复
热议问题