android - Firebase Cloud Functions 在写入后立即删除数据
问题描述
我已经实现了 Firebase Cloud Functions 来从 Firebase 数据库中删除数据。我的每个孩子都有一个时间戳,所以我想在数据超过 2 小时时删除数据,而不是在 2 小时后删除,而是在写入数据库后立即删除孩子。
这是云函数代码:
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 = 2 * 60 * 60 * 1000; // 2 Hours in milliseconds.
/**
* This database triggered function will check for child nodes that are older than the
* cut-off time. Each child needs to have a `timestamp` attribute.
*/
exports.deleteOldItems = functions.database.ref('/database/{pushId}').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('timeStamp').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);
});
{
"app_title" : "app",
"database" : {
"-Lm3gJ16yk5ZNdt8z2PJ" : {
"message" : "ok",
"timeStamp" : "1565594302830",
"userModel" : {
"email" : "abcd@yahoo.com",
"name" : "Microsoft",
"photo" : "https://graph.facebook.com/"
}
}
}
}
我已经多次搜索这个解决方案,但没有从任何地方得到它。谁能帮帮我吗。
解决方案
您的时间戳存储为字符串,而代码假定它是一个数字。我强烈建议修复编写时间戳的代码,以便将其存储为数字。
但与此同时,您可以使用以下命令查询字符串:
const oldItemsQuery = ref.orderByChild('timeStamp').endAt(""+cutoff);
推荐阅读
- electron - 如何在 Electron 中制作一个透明的加载 GIF 窗口?
- android - 是否可以编写脚本将 PWA 应用程序添加到主屏幕?
- python - Python断言列表中的所有元素不是无
- html - 如何使用图像替换 Navbar.brand?
- python - 使用 scons 0.98.1 和 python2.7 无法使用旧版本构建 gem5(stt/sdo/invisispec)
- javascript - TypeError:无法读取未定义的属性(读取“地图”)ReactJs从文件中获取数据
- c# - 比赛开始创建房间后,Photon Unity中所有人离开后房间会消失吗?
- asp.net-core - 为使用 HotChocolate 框架和 ASP.NetCore 5.0 构建的 GraphQL 端点设置 Windows 身份验证
- vue.js - Vue/Nuxt.js 图片幻灯片
- javascript - 如何使用 socket.io 检索客户端