Home > Software engineering >  What happens to the reference field when referenced document is deleted in Firestore?
What happens to the reference field when referenced document is deleted in Firestore?

Time:11-27

I have looked at What is Firestore Reference data type good for? but I don't see mentioned anywhere what happens to the reference field/link when the referenced document is deleted because I want to automatically delete the referencing document as well.

So my question is does the reference field become null or do I have to manually query to check if the referenced doc still exists or not?

I imagine the latter case would involve a lot of read operations.

Here's how I think the former case would be


ref.addSnapshotListener((value, error) -> {
    for (QueryDocumentSnapshot queryDocSnap: value){
        DocumentReference docRef = queryDocSnap.get("ref");
        if (docRef == null){
            // delete queryDocSnap
        } else{
            // do something }
    }
});


CodePudding user response:

Does the reference field become null or do I have to manually query to check if the referenced doc still exists or not?

It doesn't. You have to check that yourself. So if you have a reference that points to a document that is deleted, the reference doesn't become null. There is no built-in mechanism for that. To overcome this situation, before deleting a particular document, check if the corresponding reference exists in other documents. If it exists, then set the field to null, otherwise, take no action.

I imagine the latter case would involve a lot of read operations.

You'll always have to pay a number of read operation that is equal to the number of documents that is returned by the query that searches for the existence of a particular reference. For example, if a particular reference exists in 10 documents, then you'll have to pay 10 read operations 10 write operations since you need to set that field to null.

  • Related