首页 > 解决方案 > 无法在firebase实时数据库中写入

问题描述

  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;
       }
  });

我正在尝试在 firebase 实时数据库中添加电子邮件,但无法添加。谁能帮我纠正一下?

标签: javascriptfirebasefirebase-realtime-database

解决方案


以下代码应该可以工作。在由后台事件触发的云函数中,您必须返回一个承诺(或在某些情况下返回一个值,例如return false;)。

此外,由于您在数据库中多次写入forEach(),因此您不能set()在同一引用中多次使用该方法,因为您将覆盖之前的每次写入。您应该使用该update()方法(文档在此处)。

  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);  
    });
  });

最后,我建议您观看 Firebase 团队的以下两个视频,其中详细介绍了如何编写 Cloud Functions,特别是您必须返回 Promise 的事实:

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

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

第一个更多关于通过 HTTP 请求触发的 HTTP 函数(因此不使用后台事件),而第二个侧重于背景事件触发的函数,但建议先观看第一个,然后再观看第二个。


推荐阅读