云函数onUpdate:无法读取未定义的属性"forEach" [英] Cloud functions onUpdate: Cannot read property 'forEach' of undefined

查看:112
本文介绍了云函数onUpdate:无法读取未定义的属性"forEach"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我正在尝试更新项目中的图片. 我可以在Cloud Fire商店中更新图片网址. 但是我也想使用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.

这是我的数据结构.

This is my data structure.

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

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

这篇关于云函数onUpdate:无法读取未定义的属性"forEach"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆