I am retrieving data (and sending it to PubSub) from multiple documents that is being written in batch into a Firestore collection. This is my code:

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

I'm not sure if it's the batch issue that is causing this, but my other onWrite code is working (data not written in Batch into 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);
        })
});

I get this error from the 1st code above: JSONstringFromFS1=undefined from the functions log file.

1) Does batch writing into Firestore "slows" down the writing into the database and is therefore giving me this error?

2) If the answer is yes, how do I circumvent this?

3) Is there another way I can read all documents from /Org/{root}/ABC/{abc}/DEF/{def}/GHI/{ghi} ?

Thank you.

1 Answers

2
Renaud Tarnec On Best Solutions

The problem comes from the fact that you have to do

const stringFromFS1 = snap.data();

instead of

const stringFromFS1 = snap.data;

data() is a method and not a property, see https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentSnapshot#data.

Note that for the onWrite() triggered Cloud Function you correctly call the method with change.after.data().