j.Doe
j.Doe

Reputation: 212

Firebase cloud function use current value and not value when function was initially called

Not sure if this is even possible with firebase cloud functions.

Let's assume, I want to trigger a cloud function onCreate on all documents in a specific collection. After creation, the cloud function should add another document in a different collection. Passing a value from the manually created document.

Sure, that works!:

export const createAutomaticInvoice = functions.firestore.document('users/{userId}/lessons/{lesson}').onCreate((snap, context) => {

    let db = admin.firestore();
    let info = snap.ref.data()    

    db.collection('toAdd').add({
        info: info
    })


})

But if I create a document within users/{userId}/lessons/ and change the value of info directly afterwards, before the cloud function is triggered, the cloud function takes the old value of info as supposed to the one it was changed to.

Is this expected behaviour? For me it is definetely not as I would assume that it takes the values at runtime.

How can I make my example work as expected?

Upvotes: 3

Views: 37

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317828

This is the expected behavior - the function is going to execute as soon as possible after that document is created. The snapshot is always going to contain the contents of the document as it was originally created. It's not going to wait around to see if that document changes at some point in the future, and it's not going to try to query that document in case it might have changed.

If you want to handle updates to a document, you should also be using an onUpdate trigger to know if that happens.

Upvotes: 1

Related Questions