javascript - Delete older firebase data
问题描述
I want to delete data older than 2 hours. I tried another SO answer but it did not solve my problem.
https://stackoverflow.com/a/32012520/2872091
Now, let me show my code and firebase structure
Firebase Structure:
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);
});
});
Then, I deployed this js file to my firebase.
firebase deploy --only functions
It is deployed successfully, terminal said "Deploy complete!". And I can see deleteOldItems function in Firebase functions.
As a result, my structure and code is like this. And nothing changed when a new data is added to Room/English node. Data (older than 2 hours) in this node is not deleted. How can I solve the problem? What is my mistake?
解决方案
exports.deleteOldItems = functions.database.ref('/path/to/items/{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('timestamp').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);
});
});
推荐阅读
- primefaces - 如何覆盖 ap:confirmDialog 中的自定义严重性图标
- javascript - 为什么我的 javascript 代码没有执行并且说不是有效的 mime 类型?
- ubuntu - Hive 卡住查询,可能是什么问题?
- javascript - 有没有办法使用 jsZIP 将多个 jsPDF 输出保存到单个 ZIP 中?
- python - 提高 pandas 数据框的性能
- datetime - 如何解决动态日期模板的问题?
- c++ - GCC 4.4 中的 OpenSSL 1.1.1a OPENSSL_API_COMPAT 问题
- java - JavaFX,为什么锚窗格中的像素值加倍?例如,如果您输入 10.5 会发生什么?
- javascript - 当“a href”为空时如何删除“css类”
- sql-server - EntityType 没有在名为“NameId”的列上定义键