【发布时间】:2018-07-12 21:24:49
【问题描述】:
我想删除超过 2 小时的数据。我尝试了另一个 SO 答案,但没有解决我的问题。
https://stackoverflow.com/a/32012520/2872091
现在,让我展示一下我的代码和 Firebase 结构
Firebase 结构:
Index.js:
const functions = require('firebase-functions');
exports.deleteOldItems = functions.database.ref('Room/English/{pushId}')
.onWrite(event => {
var ref = event.data.ref.parent; // reference to the items
var now = Date.now();
var cutoff = now - 2 * 60 * 60 * 1000;
var oldItemsQuery = ref.orderByChild('time').endAt(cutoff);
return oldItemsQuery.once('value', function(snapshot) {
// create a map with all children that need to be removed
var updates = {};
snapshot.forEach(function(child) {
updates[child.key] = null
});
// execute all updates in one go and return the result to end the function
return ref.update(updates);
});
});
然后,我将此 js 文件部署到我的 firebase。
firebase deploy --only functions
部署成功,终端提示“部署完成!”。我可以在 Firebase 函数中看到 deleteOldItems 函数。
结果,我的结构和代码是这样的。当新数据添加到 Room/English 节点时,没有任何变化。此节点中的数据(超过 2 小时)不会被删除。我该如何解决这个问题?我的错误是什么?
【问题讨论】:
-
Cloud Functions 的签名已更改。我更新了我的原始答案,并将再次关闭您的问题。请注意,此处记录了此更改:firebase.google.com/docs/functions/…,并且链接的示例存储库也已更新:firebase.google.com/docs/functions/…。
-
非常感谢您,Puffelen 先生。你解决了我的问题 :) 祝你有美好的一天!
标签: javascript firebase firebase-realtime-database google-cloud-functions