【发布时间】:2019-01-26 13:37:46
【问题描述】:
我是使用 Firebase 函数的新手。
7 天后(按时间戳计算)我想从我的数据库中删除一个 Post 节点,然后从评论和反应中删除所有节点,这些节点包含对该帖子的引用。之后,如果帖子的 photoVideoPath 是 firebase 存储的引用,我想从我的存储中删除该对象。
我的数据库结构是:
Post: {
PostKey: {
date: xx/xx/xxxx
timestamp: xxxxxxxx
photoVideoPath: xxxxxxxxxx
title: xxxxxxxxxxx
}
[...]
}
Comment: {
PostKey: {
date: xx/xx/xx
hours: xx:xx
user: idUser
text: xxxxxxxxxx
}
[...]
}
Reaction: {
PostKey: {
type: xxxxxx
user: idUser
}
[...]
}
我写的代码是:
exports.deleteOldItems = functions.database.ref('/Post/{pushId}').onWrite((change) => {
const ref = change.after.ref.parent; // reference to the parent
const now = Date.now();
const cutoff = now - CUT_OFF_TIME;
ref.orderByChild('timestamp').endAt(cutoff).once('value', res => {
// create a map with all children that need to be removed
const updates = {};
res.forEach(child => {
updates[child.key] = null;
});
ref.update(updates);
functions.database.ref('/Reaction/').child(res.key).remove();
functions.database.ref('/Comment/').child(res.key).remove();
if (!res.val().photoVideoPath.startsWith("data:image/") && !res.val().photoVideoPath.startsWith("http")) {
const filePath = res.val().title + res.val().data.replace("/", "").replace("/", "") + res.val().photoVideoPath
const bucket = googleCloudStorage.bucket('xxxxxxx.appspot.com')
const file = bucket.file(filePath)
file.delete().then(() => {
return console.log(`Successfully deleted photo`)
}).catch(err => {
return console.log(`Failed to remove photo, error: ${err}`)
});
}
});
});
我做错了什么?谢谢大家,祝你有美好的一天
【问题讨论】:
标签: javascript firebase firebase-realtime-database google-cloud-functions firebase-storage