How to use a reference Field in Firestore to delete another Document with onDelete Trigger

Viewed 30

I am new with Firebase and I am using the field reference so I can link different documents in different collections. If the user want to delete his account so everything were connected with references should also be deleted automatically.(In the image the company of the user will also be deleted when the user delete his account). So in my code I can delete the user but I couldn't delete the company using the reference. Maybe can someone help?

exports.userDelete =   functions.auth.user().onDelete ( user => {
    firestore.collection("users").doc(user.uid).delete();
    //user.company.delete(); not working
   })

Firebase photo

1 Answers

Use the promise returned by delete() to tell the function to wait for that asynchronous work to complete before terminating the function.

exports.userDelete = functions.auth.user().onDelete (async user => {
    await firestore.collection("users").doc(user.uid).delete();
    //user.company.delete(); not working
})

In order to write effective functions, you will definitely need to understand JavaScript promises and asynchronous programming. Otherwise your function will always fail without helpful error messages. I suggest reviewing the documentation about that.

https://firebase.google.com/docs/functions/terminate-functions

Related