我的目标是删除所有使用Firebase Cloud Functions和实时数据库发送的消息节点24小时。我尝试从this post复制并粘贴答案,但是由于某些原因,消息在创建后立即删除,而不是在24小时后删除。如果有人可以帮助我解决这个问题,我将不胜感激。我根据相同的问题尝试了多种不同的答案,但它们对我没有用。
这是我的index.js文件:
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
// Cut off time. Child nodes older than this will be deleted.
const CUT_OFF_TIME = 24 * 60 * 60 * 1000; // 2 Hours in milliseconds.
exports.deleteOldMessages = functions.database.ref('/Message/{chatRoomId}').onWrite(async (change) => {
const ref = change.after.ref.parent; // reference to the parent
const now = Date.now();
const cutoff = now - CUT_OFF_TIME;
const oldItemsQuery = ref.orderByChild('seconds').endAt(cutoff);
const snapshot = await oldItemsQuery.once('value');
// create a map with all children that need to be removed
const updates = {};
snapshot.forEach(child => {
updates[child.key] = null;
});
// execute all updates in one go and return the result to end the function
return ref.update(updates);
});
答案 0 :(得分:0)
在注释中,您表示您正在使用Swift。从中和屏幕截图可以看出,您存储的时间标记是自1970年以来的秒数,而Cloud Functions中的代码假定该时间单位是毫秒。
最简单的解决方法是:
// Cut off time. Child nodes older than this will be deleted.
const CUT_OFF_TIME = 24 * 60 * 60; // 2 Hours in seconds.
也请在这里查看我的答案:How to remove a child node after a certain date is passed in Firebase cloud functions?