【问题标题】:Retrieving data from Firestore snap.data of an onCreate but have undefined error从 onCreate 的 Firestore snap.data 中检索数据但有未定义的错误
【发布时间】:2019-05-03 10:12:19
【问题描述】:

我正在从批量写入 Firestore 集合的多个文档中检索数据(并将其发送到 PubSub)。这是我的代码:

exports.orderItemstoPubSub = functions
.firestore
.document('Org/{root}/ABC/{abc}/DEF/{def}/GHI/{ghi}')
.onCreate((snap, context) => {

    //publish a message to Cloud Pub/Sub topic
    const stringFromFS1 = snap.data;

    const JSONstringFromFS1 = JSON.stringify(stringFromFS1);
    console.log(`JSONstringFromFS1=${JSONstringFromFS1}`)
    const dataBuffer = Buffer.from(JSONstringFromFS1)

    return pubsubClient
        .topic('projects/pubsubclient123-test/topics/pubsubclient123-test')
        .publish(dataBuffer)
        .then(messageId => {
            console.log(`Message ${messageId} published.`)
        })
        .catch(err => {
            console.error('ERROR:', err);
        })    
});

我不确定是否是批处理问题导致此问题,但我的其他 onWrite 代码正在运行(数据未以批处理方式写入 Firestore):

exports.orderIDtoPubSub = functions
.firestore
.document('Org/{root}/ABC/{abc}/DEF/{def}')
.onWrite((change, context) => {

const stringFromFS = change.after.exists ? change.after.data() : null;

    stringFromFS.abc=context.params.abc;
    stringFromFS.root=context.params.root;

    const JSONstringFromFS = JSON.stringify(stringFromFS);
    console.log(`JSONstringFromFS=${JSONstringFromFS}`)
    const dataBuffer = Buffer.from(JSONstringFromFS)

    return pubsubClient
        .topic('projects/pubsubclient123-test/topics/pubsubclient123-test')
        .publish(dataBuffer)
        .then(messageId => {
            console.log(`Message ${messageId} published.`)
        })
        .catch(err => {
            console.error('ERROR:', err);
        })
});

我从上面的第一个代码中得到这个错误:来自函数日志文件的JSONstringFromFS1=undefined。

1) 批量写入 Firestore 是否会“减慢”写入数据库的速度并因此给我这个错误?

2) 如果答案是肯定的,我该如何规避这个问题?

3) 有没有其他方法可以读取来自/Org/{root}/ABC/{abc}/DEF/{def}/GHI/{ghi} 的所有文档?

谢谢。

【问题讨论】:

    标签: typescript firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    问题来自于你必须做的事实

    const stringFromFS1 = snap.data();
    

    而不是

    const stringFromFS1 = snap.data;
    

    data() 是方法而非属性,请参阅https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentSnapshot#data。

    请注意,对于 onWrite() 触发的云函数,您可以正确地使用 change.after.data() 调用该方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      • 2020-04-07
      • 1970-01-01
      • 2017-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多