【发布时间】:2019-10-12 12:44:20
【问题描述】:
我的目标是在使用 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);
});
【问题讨论】:
-
许多开发人员报告了实现此功能的问题,但就像here last week 一样,问题始终在于他们所做的更改。例如:登录时
cutoff的值是多少?这与 JSON 中seconds的值相比如何? -
@FrankvanPuffelen 很抱歉提出这个问题,但您记录它是什么意思以及如何记录?存储的秒数来自 1970 年以来的秒数
-
console.log(cutoff)然后检查您的 Cloud Functions 的日志记录面板。如果您是 JavaScript 新手,Cloud Functions for Firebase 并不是学习它的最佳方式。我建议先阅读Firebase documentation for Web developers。这涵盖了许多基本的 JavaScript 和 Firebase 数据库交互。您还可以在本地 Node.js 进程中使用 Admin SDK,该进程可以使用本地调试器进行调试。完成这些之后,您将能够更好地为 Cloud Functions 编写代码。 -
@FrankvanPuffelen 对于迟到的回复,我深表歉意。我记录了它并在控制台中得到了 1559331549417 。接下来我该怎么办?感谢您对此提供的帮助
-
@DheerajMahra 是的,但您仍然可以获得使用免费限制的 spark 计划。您还可以设置付款限额。
标签: node.js firebase firebase-realtime-database google-cloud-functions