Vishu
Vishu

Reputation: 35

not able to write in firebase realtime database

  exports.sendBigQueryData = 
  functions.analytics.event('buy_from_shop').onLog((event) => {
  const bigQuery = bigquery({ projectId:  });
  bigQuery.query({
  query: 'select email from table',
  useLegacySql: false
        }).then(function (results) {
        console.log(results);
        var ref = admin.database().ref("BigQueryData");// this should 
       //create a node with name BigQueryData and store the emails 
            there!

        var rows = results[0]; //get all fetched table rows
         rows.forEach(function(row){ //iterate through each row
            ref.push().set({ 
                email:row['email']


            });
        });
        //return result
    });
     {
      console.log(email,points);
      return 0;
       }
  });

I m trying to add the email in firebase realtime db but not able to. can anyone help me to make this correct?

Upvotes: 0

Views: 145

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83058

The following code should work. Within a Cloud Function triggered by a background event you must return a promise (or in certain cases a value, e.g. return false;).

In addition, since you are writing several times in the database with forEach(), you cannot use the set() method several times at the same reference because you will overwrite each previous write. You should use the update() method (doc is here).

  exports.sendBigQueryData = 
  functions.analytics.event('buy_from_shop').onLog((event) => {
      const bigQuery = bigquery({ projectId:  });

      return bigQuery.query({   // <- here add a return
        query: 'select email from table',
         useLegacySql: false

      }).then(function (results) {
         console.log(results);
         //.....

         let updates = {};

         const rows = results[0]; //get all fetched table rows
         rows.forEach(function(row){ //iterate through each row
            const newPostKey = admin.database().ref().child('BigQueryData').push().key;

            updates['/BigQueryData/' + newPostKey] = {email:row['email']};
        });

        return admin.database().ref().update(updates); // <- we return a promise

    }).catch(function (err) { // <- You have to catch the possible errors as well
       console.log(err);  
    });
  });

Finally, I would suggest you watch the following two videos from the Firebase team which detail how Cloud Functions shall be written, and in particular the fact that you must return promises:

https://www.youtube.com/watch?v=7IkUgCLr5oA

https://www.youtube.com/watch?v=652XeeKNHSk

The first one is more about HTTP Functions that are triggered through an HTTP request (so not with a background event) while the second is focused on background event triggered Functions, but it is advised to watch the first one before watching the second one.

Upvotes: 2

Related Questions