skip to Main Content

I have a Firestore collection called "documents":

db
 documents
   $documentId

I have created a cloud function that fires each time a new document is added/deleted. This function increments/decrements a number in the real-time database at:

db
 documents
   $documentId: 10,000

My boss asked me to implement a delete account option that can delete all user documents.

What I have tried is to create another cloud function that fires when the user deletes the account in authentication. The problem arises when I delete all the documents in the collection, because for each document delete, the first function fires and decrements the number in the real-time database and I don’t want the function to be invoked. How to avoid the first cloud function to decrement the number in real-time database, when I delete all documents in Firestore using cloud function?

2

Answers


  1. Do you save the user id in the documents collection? if yes, when onDelete is called you can check if userId != "userId_deleted" and then call the code to decrement or not

    Login or Signup to reply.
  2. There is no way to dynamically control whether the Cloud Function fires or not.

    The options I can think of:

    • Filter based on some value in the documents, such as FaBotch says in their answer – and as Doug answered here
    • Before starting the delete, write some other flag value somewhere to indicate that you don’t want to further process this user’s data, and then read that in the Cloud Function.
    • Let the Cloud Function finish its decrement counts, and then at some point post-process the counter.

    While that last one may sound hacky, it’s actually what I often end up doing: removing spurious counters once a day or so.

    For completeness: the Firebase CLI has a database:import command that takes a --disable-triggers flag that is somewhat what you want, but that only exists on the CLI (not the API), it doesn’t work for deletes, and does not exist for Firestore.

    Also see:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search