Home > Software design >  Firebase setting value from another key
Firebase setting value from another key

Time:05-10

I have a firebase function that sets two values to zero. Is there a way to set the value of "lastDaily" to whatever the value of "click" is before setting click to 0?

exports.dailyReset = functions.pubsub.schedule("01 0 * * *")
    .timeZone("Europe/London")
    .onRun((context) => {
      dbCon.once("value", function(snapshot) {
        snapshot.forEach(function(child) {
          child.ref.update({
            lastDaily: 0,
            click: 0,
          });
        });
      });
    });

CodePudding user response:

The following should do the trick (untested):

exports.dailyReset = functions.pubsub.schedule("01 0 * * *")
    .timeZone("Europe/London")
    .onRun(async (context) => {
        
        const snapshot = await dbCon.get();
        
        const promises = [];
        
        snapshot.forEach(child => {
            const oldClickValue = child.val().lastDaily;
            promises.push(child.ref.update({
                lastDaily: oldClickValue,
                click: 0,
            }));
        })
        
        return Promise.all(promises);
        
    });

Note that we use Promise.all() in order to return a Promise when all the asynchronous work is complete. For the same reason note that we use the get() method, which returns a Promise.


Another solution, instead of Promise.all(), would be to use the update() method as shown in this documentation section.

  • Related