javascript - 无法在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 实时数据库中添加电子邮件,但无法添加。谁能帮我纠正一下?
解决方案
以下代码应该可以工作。在由后台事件触发的云函数中,您必须返回一个承诺(或在某些情况下返回一个值,例如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 函数(因此不使用后台事件),而第二个侧重于背景事件触发的函数,但建议先观看第一个,然后再观看第二个。
推荐阅读
- xamarin - InputJar和ReferenceJar的Xamarin绑定库组合?
- javascript - 如何在 NodeJS express 上处理动态添加的 html 表单
- powershell - Powershell - 需要帮助将 IP 地址从测试连接导出到 CSV
- r - R:从固定时期估计的方程中提前预测
- c++ - 在 C++ 中查找像素 RGB 数据的最快方法是什么?
- javascript - 在 Firestore 中创建子集合会生成两个具有相同 id 的文档(而不是更新预先存在的文档)
- html - iOS 键盘上推内容
- react-bootstrap - Col 没有与 Form 并排对齐
- python - 如何将多个字典中的数据与重复键合并?
- reactjs - 如何泛型化 React 组件 props 并扩展泛型 props 类型