如何使用 Firebase 功能从存储中删除文件?

问题描述 投票:0回答:1

我有 Firestore 数据库,其文档结构如下

startDate - String
endDate - String
pages - Array(String)

并通过以下路径存储带有文件的数据库:

/pages/fileID

我使用 Firebase Functions 运行 cron 作业来删除陈旧数据。当我从 Firestore 中删除记录时,我也想从存储中删除与此记录文件相关的文件,但收到错误:没有此类对象(来自 Google Cloud 控制台日志)。如何正确地做到这一点?

const functions = require("firebase-functions")
const admin = require("firebase-admin")
admin.initializeApp({ storageBucket: "..." })
var firestore = admin.firestore()

exports.deleteEntries = functions.pubsub.schedule("* * * * *")
    .onRun(async () => {
        const bucket = admin.storage().bucket()

        const timeElapsed = Date.now()
        const today = new Date(timeElapsed)

        const albumsRef = firestore.collection('albums')
        const albums = await albumsRef.where('endDate', '<', today.toISOString()).get()
        albums.forEach(async snapshot => {
            snapshot.ref.delete() // This works fine, file removed from Firestore - success
            const promises = []
            await snapshot.ref.get().then(doc => {
                doc.data().pages.forEach(path => { // Error: No such object
                    promises.push(bucket.file(`/${path}`).delete())
                })
            })
            await Promise.all(promises)
        })
        return null
    })
node.js firebase google-cloud-firestore google-cloud-functions google-cloud-storage
1个回答
0
投票

不建议混合使用 forEach 和 async/await,请参阅“JavaScript:async/await 与 forEach()”和“将 async/await 与 forEach 循环一起使用”。

以下代码应该可以解决问题(未经测试):

exports.deleteEntries = functions.pubsub
  .schedule("* * * * *")
  .onRun(async () => {
    const bucket = admin.storage().bucket();

    const timeElapsed = Date.now();
    const today = new Date(timeElapsed);

    const albumsRef = firestore.collection("albums");
    const albums = await albumsRef
      .where("endDate", "<", today.toISOString())
      .get();

    const promises = [];

    albums.forEach((albumSnapshot) => {
      promises.push(albumSnapshot.ref.delete()); // This works fine, file removed from Firestore - success
      albumSnapshot.data().pages.forEach((path) => {
        promises.push(bucket.file(`/${path}`).delete());
      });
    });

    await Promise.all(promises);
    return null;
  });
© www.soinside.com 2019 - 2024. All rights reserved.