javascript - 如何在 Firebase Function 中访问 Firebase 数据库的快照?
问题描述
每小时,我希望我的 firebase 函数查看我的数据库,读取一个值,从这个旧值计算一个新值,然后在数据库中更新它。我无法访问数据的快照。具体来说,
exports.scheduledFunction = functions.pubsub.schedule('every 1 hour').onRun((context) => {
const ref = functions.database.ref('/users/test_user/commutes');
ref.once('value',function(snapshot) {
// do new calculation here
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
return null;
});
我收到一个 :functions: TypeError: ref.once is not a function
错误。
如何访问我的 firebase 实时数据库中的值并从 Firebase 函数更新它?
解决方案
您正在尝试使用 firebase-functions SDK 来查询数据库。它不能那样做。您必须使用Firebase Admin SDK进行查询。
你需要像这样开始(不完整,但你应该能够看到你需要做什么)。在全局范围内导入和初始化:
const admin = require('firebase-admin')
admin.initializeApp()
然后在你的函数中,使用它。确保正确使用 Promise。
const ref = admin.database().ref('...')
return ref.once('value').then(snapshot => {
// work with the snapshot here, and return another promise
// that resolves after all your updates are complete
})
推荐阅读
- python - python中localhost上的HTTP删除请求
- clojure - Clojure.Spec 派生或别名另一个规范
- r - 删除不均匀 x 轴时间序列图中 ggplot2 中的空列
- python - 在独立于随机种子的pytorch中使用dropout时,丢弃的节点会随机变化吗?
- python - 在 Python 的嵌套列表中查找最大值
- mysql - 如何将此 MySql 子查询转换为连接查询?
- bitbucket - 将审阅者添加到 PR 时检索 BitBucket 1.0 REST API
- python - 在 C++ 中写入 hdf5 文件会导致数据在某些时候被截断
- python-3.x - 如何在 python 3.8.5 中使用 isdigit()?
- amazon-web-services - 如何使用 ECS 和 EC2 实例集群实现零停机部署