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

人气:911 发布:2022-10-16 标签: javascript node.js firebase google-cloud-storage google-cloud-functions

问题描述

现在我正在尝试更新我的项目中的图片.我可以更新云火商店中的图片网址.但我也想使用firebase云功能从云存储中删除之前的图片.

Now I am trying to update the picture in my project. I could update the picture url in the cloud fire store. But also I want to delete the previous picture from the cloud storage using firebase cloud functions.

我想要实现的是,当我上传新图片时,从云存储中删除之前的图片.

What I want to achieve is, to delete the previous picture from the cloud storage when I upload the new picture.

这是我的数据结构.

我有样品"产品"中的字段收藏.当样本"中的图片字段已更新,我想删除云存储中的原始图片.

I have "sample" field in "Product" collection. When the picture in "sample" field is updated, I want to delete the original picture in the cloud storage.

但我在云函数日志控制台中遇到错误.

But I got an error in the cloud functions log console.

TypeError: 无法读取未定义的属性forEach"

TypeError: Cannot read property 'forEach' of undefined

这是我的云函数代码.

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)
})

我想修正这个错误.

推荐答案

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

onUpdate is only looking at one document and it would appear from your screenshot of your doc that snap.before.data().sample is a string where your code is treating it like an object, or even a query snapshot?

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

Unless I've misunderstood, does this is correct your code?

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
 
});

673