【发布时间】:2020-04-29 19:06:06
【问题描述】:
当从实时数据库中删除数据节点时,我想从存储中删除文件。要删除的文件的名称是在删除之前取的。文件名保存在名为“imageTitle”的子节点中。该代码在实现文件删除代码之前运行良好。我的意思是节点被完全删除了。
当我实现文件删除代码时,其余部分不起作用,但没有任何错误。文件删除后的代码不起作用。我不知道为什么。
这是一个学术期末项目。
bucket 中有一个名为 images 的文件夹,我需要删除的文件就在里面。文件名取自要在名为 imageTitle 的实时数据库中删除的节点中的子节点:
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.changetime = functions.database.ref('/posts/{pushId}')
.onCreate((snapshot, context) => {
const editDate = Date.now()
datas = snapshot.val();
return snapshot.ref.update({editDate})
})
const CUT_OFF_TIME = 1 * 60 * 1000;
/**
* 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('/posts/{pushId}').onWrite(async (change,
context) => {
const ref = change.after.ref.parent; // reference to the parent
const now = Date.now();
const id = context.params.pushId;
const cutoff = now - CUT_OFF_TIME;
const oldItemsQuery = ref.orderByChild('createdDate').endAt(cutoff);
const snapshot = await oldItemsQuery.once('value');
const getImageTitle = admin.database().ref(`/posts/${id}/imageTitle`).once('value');
return getImageTitle.then(imageTitle => {
console.log('post author id', imageTitle.val());
const imageName = imageTitle.val();
const filePath = 'images/' + imageName;
const path = `images/${imageName}`;
const bucket = app.storage().bucket();
return bucket.file(path).delete().then(() =>{
console.log(`File deleted successfully in path: ${imageName}`)
/* The problem is here. the code doesn't work after file.delete function. no errors. but doesn't work
if I remove that piece of code the other codes work fine. I mean the realtime database nodes get deleted and updated perfectly */
const updates = {};
snapshot.forEach(child => {
updates[child.key] = null;
if(updates[child.key] == null){
admin.database().ref(/post-likes/+id).remove();
}
})
return ref.update(updates);
});
});
[my storage looks like this][1]});
bucket 中有一个名为 images 的文件夹,我需要删除的文件就在里面。文件名取自实时数据库中要删除的节点中的子节点imageTitle:
【问题讨论】:
-
您似乎在此代码的引用中缺少路径周围的引号:
admin.database().ref(/post-likes/+id).remove()不确定这是否是您唯一的问题。在我的手机上执行此操作。 -
那部分代码工作正常。问题在于文件删除。我只是不知道如何实现它
标签: javascript firebase firebase-realtime-database google-cloud-functions