0
votes

I've written a few cloud functions for my project so far. I was building a new function addUserToEmailLists and testing it to see if it got called simply by setting a field in a document when that document was created, onCreate()

exports.addUserToEmailLists = functions.firestore.document('Users/{userID}/jobPreferences/myPreferences').onCreate(() => {
  console.log('Function called!'); //remove this and it doesn't work
  return db.doc(`DatabaseInfo/accounts`).set({ //update the number of preferences
        preferencesSet: 1
  }).catch(error=>{
        console.log(error);
        return error;
  });
})

At first I had just from the line with return straight down in the function and the Firebase log kept saying the function was executed with status 200 but the document wasn't being set. Just as a last resort I added the console.log('Function called!'); and it worked! Then I removed the line and deployed once more and it failed to set the field accountsCreated (did that a couple more times waiting at least 3 minutes before trying to trigger the function again to be sure). My other functions don't have any console.log() statements so I'm at a loss for what causes this behaviour. Does anyone have a suggestion?

1
Hi Ramjit. Did you manage to find a solution? I have the reverse of the issue! When I comment out console.log it works. When I have it included it does not - Vinayakaram Nagarajan
I tried to reproduce this, but that exact function worked as expected (on an arbitrary onCreate event in my database). Creating a document at the right spot set the value in the specified document. This happened regardless of if the log statement was there. The only thing possibly related was that the console did not automatically update if the DatabaseInfo collection was created by this operation -- I had to manually refresh. But the update always happened. Need more information to reproduce. - robsiemb
@VinayakaramNagarajan no, unfortunately I haven't but this issue was during v6 of firebase functions. Since they've upgraded to v7 I'm not sure if the issue would still be present. - S.Ramjit
@VinayakaramNagarajan I know this is late but can post a new question with a code example of the issue you were having and link it here? - S.Ramjit
I already have it, actually. Had linked your question on to that: stackoverflow.com/questions/58651617/… - Vinayakaram Nagarajan

1 Answers

1
votes

Looks to me like you are calling an asynchronous function and expecting it to behave synchronously.

Perhaps the addition of a console.log entry simply gives the function the headroom it needs to complete the asynchronous work.

Try something like this:

exports.addUserToEmailLists = functions.firestore.document('Users/{userID}/jobPreferences/myPreferences').onCreate(async () => {
  await db.doc(`DatabaseInfo/accounts`).set({ //update the number of preferences
        preferencesSet: 1
  });
})