无法写入firebase实时数据库

时间:2018-06-08 10:24:04

标签: javascript firebase firebase-realtime-database

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body, html {
    height: 100%;
    margin: 0;
}

body {
    /* The image used */
    background-image: url("http://www.gstatic.com/webp/gallery/1.jpg");

    /* Full height */
    height: 100%;

    /* Center and scale the image nicely */
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}
</style>
</head>
<body>

<div class="bg"></div>

<p>This example creates a full page background image. Try to resize the browser window to see how it always will cover the full screen (when scrolled to top), and that it scales nicely on all screen sizes.</p>

</body>
</html>

我正在尝试在firebase实时数据库中添加电子邮件但不能。 任何人都可以帮助我做到这一点吗?

1 个答案:

答案 0 :(得分:2)

以下代码应该有效。在由后台事件触发的云功能中,您必须返回承诺(或在某些情况下返回值,例如return false;)。

此外,由于您使用forEach()在数据库中多次写入,因此您不能在同一个引用中多次使用set()方法,因为您将覆盖每个先前的写入。您应该使用update()方法(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);  
    });
  });

最后,我建议您观看Firebase小组中的以下两个视频,详细说明如何编写云功能,特别是您必须返回承诺的事实:

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

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

第一个更多是关于通过HTTP请求触发的HTTP函数(因此不是背景事件),而第二个关注于背景事件触发函数,但建议在观看第二个之前观看第一个一。