为了账号安全,请及时绑定邮箱和手机立即绑定

云函数 onUpdate:无法读取未定义的属性“forEach”

云函数 onUpdate:无法读取未定义的属性“forEach”

斯蒂芬大帝 2023-08-05 21:01:58
现在我正在尝试更新我的项目中的图片。我可以更新云火商店中的图片网址。但我也想使用 firebase 云功能从云存储中删除上一张图片。我想要实现的是,当我上传新图片时,从云存储中删除以前的图片。这是我的数据结构。我在“产品”集合中有“样本”字段。当“样本”字段中的图片更新时,我想删除云存储中的原始图片。但我在云函数日志控制台中收到错误。类型错误:无法读取未定义的属性“forEach”这是我的云函数代码。const functions = require('firebase-functions');const admin = require('firebase-admin');admin.initializeApp();const Firestore = admin.firestore;const db = Firestore();exports.onProductUpdate = functions.firestore.document('Product/{productId}').onUpdate(async(snap, context) => {    const deletePost = snap.before.data().sample;    let deletePromises = [];    const bucket = admin.storage().bucket();    deletePost.images.forEach(image => {        deletePromises.push(bucket.file(image).delete())    });        await Promise.all(deletePromises)})我想修复这个错误。
查看完整描述

2 回答

?
MM们

TA贡献1886条经验 获得超2个赞

onUpdate 只查看一个文档,从您的文档屏幕截图中可以看出,它snap.before.data().sample是一个字符串,您的代码将其视为一个对象,甚至是一个查询快照?


除非我误解了,否则这是正确的您的代码吗?


const functions = require('firebase-functions');

const admin = require('firebase-admin');

admin.initializeApp();


const Firestore = admin.firestore;

const db = Firestore();




exports.onProductUpdate = functions.firestore.document('Product/{productId}').onUpdate(async(snap, context) => {

    const deletePost = snap.before.data().sample;

    const bucket = admin.storage().bucket();


    await bucket.file(deletePost).delete();


    return null;   // See https://firebase.google.com/docs/functions/terminate-functions

 

});


查看完整回答
反对 回复 2023-08-05
?
慕妹3146593

TA贡献1820条经验 获得超9个赞

无论问题如何forEach,您的代码都无法工作:您尝试将 URL 传递给file()Bucket 的方法,而您应该传递此存储桶中的文件名称。


Product一种解决方案是将文件的名称保存在文档的另一个字段中。


然后,正如 Cleanbeans 所解释的,您不需要使用forEach,因为在您的 Cloud Function 中,您只处理一个 Firestore 文档。


只需使用包含文件名的其他字段并调整 Cleanbeans 的解决方案,如下所示:


exports.onProductUpdate = functions.firestore.document('Product/{productId}').onUpdate(async(snap, context) => {

    const deleteFileName = snap.before.data().fileName;

    const bucket = admin.storage().bucket();


    await bucket.file(deleteFileName).delete())


    return null;   // Don't forget to return null for example (or an Object or a Promise), to indicate to the platform that the CF can be cleaned up. See https://firebase.google.com/docs/functions/terminate-functions


});


查看完整回答
反对 回复 2023-08-05
  • 2 回答
  • 0 关注
  • 82 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信