【发布时间】:2020-01-12 11:16:00
【问题描述】:
我正在为 Firebase Cloud Functions 编写一个函数,我可以在其中从 Firebase 数据库中删除旧节点。每个节点上都有一个指向保存在 Firebase 存储中的文件的链接。
数据库结构
"data" : {
"-Lo0onTCSVeY-Kco5ujX" : {
"photo" : "https://firebasestorage.googleapis.com/v0...",
"idD" : "-Lo0onTCSVeY-Kco5ujX",
"idUs" : "jh4Ch9rBgQPwBTfv43MgNissRUP2",
"timestamp" : 1567693686925,
}
},
功能:
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
var DAY_MILLIS = 86400000 //1 Day
exports.deleteOldPosts = functions.database.ref('/data/{pushId}').onWrite(function(change) {
var ref = change.after.ref.parent; // reference to the parent
var now = Date.now();
var cutoff = now - DAY_MILLIS;
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);
});
});
我怎样才能删除文件呢? 提前致谢。
【问题讨论】:
-
将来,如果您知道文件在 Cloud Storage 中的路径,删除文件会容易得多。您现在拥有的是一个下载 URL,它在使用后端 SDK 时不容易转换为路径。如果您有路径,您只需将其提供给 Cloud Storage 节点 SDK 即可将其删除。
-
您要删除所有早于某个日期的文件吗?
标签: node.js firebase firebase-realtime-database google-cloud-functions firebase-storage