我在firebase.However上使用云函数在2小时后删除节点,当我添加一个节点时,它在数据库中一创建就会被删除
我的index.js:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const CUT_OFF_TIME = 2 * 60 * 60 * 1000; // 2 Hours in milliseconds
exports.deleteOldItems = functions.database.ref('/posts/{randomID1}/{randomID2}/timestamp')
.onWrite(function(change) {
var ref = change.after.ref.parent; // reference to the parent
var now = Date.now();
var cutoff = now - CUT_OFF_TIME;
var oldItemsQuery = ref.orderByChild('timestamp').endAt(cutoff);
return oldItemsQuery.once('value').then(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);
});
});我的数据库结构:
"posts" : {
"randomID1" : {
"randomID2" : {
"timestamp" : 1557842159
}
},
"randomID3" : {
"randomID4" : {
"timestamp" : 1557842203
}
},发布于 2019-05-15 00:24:05
时间戳以秒为单位存储,而不是以毫秒为单位。因为您的代码使用Date.now,它返回以毫秒为单位的时间戳,所以您要比较的是相差1000倍的值。
最简单的解决方案是:
const CUT_OFF_TIME = 2 * 60 * 60; // 2 Hours in seconds发布于 2019-05-15 10:55:56
您正在比较以毫秒为单位的时间戳和以秒为单位的时间戳。
var cutoff = now - CUT_OFF_TIME; -截止值以毫秒为单位
您需要更改秒数并将Date.now()转换为CUT_OFF_TIME。
https://stackoverflow.com/questions/56133351
复制相似问题