Javascript Firebase云功能是立即删除节点,而不是在2小时后删除
我在firebase上使用云函数在2小时后删除节点。但是,当我添加节点时,它会在数据库中创建后立即被删除 My index.js:Javascript Firebase云功能是立即删除节点,而不是在2小时后删除,javascript,node.js,firebase,firebase-realtime-database,google-cloud-functions,Javascript,Node.js,Firebase,Firebase Realtime Database,Google Cloud Functions,我在firebase上使用云函数在2小时后删除节点。但是,当我添加节点时,它会在数据库中创建后立即被删除 My 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 ex
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
}
},
时间戳以秒为单位存储,而不是以毫秒为单位。由于您的代码使用以毫秒为单位返回时间戳的
Date.now
,因此您正在比较1000倍的值
最简单的解决方案是:
const CUT_OFF_TIME = 2 * 60 * 60; // 2 Hours in seconds
时间戳以秒为单位存储,而不是以毫秒为单位。由于您的代码使用以毫秒为单位返回时间戳的
Date.now
,因此您正在比较1000倍的值
最简单的解决方案是:
const CUT_OFF_TIME = 2 * 60 * 60; // 2 Hours in seconds
您正在比较以毫秒为单位的时间戳和以秒为单位的时间戳
var切断=现在-切断时间代码>-截止值以毫秒为单位
您需要更改截止时间
并将Date.now()
转换为秒。您正在比较以毫秒为单位的时间戳和以秒为单位的时间戳
var切断=现在-切断时间代码>-截止值以毫秒为单位
您需要更改截止时间
并将Date.now()
转换为秒