Home > Software engineering >  Need to delete null FireStore document, only have FIRDocumentReference
Need to delete null FireStore document, only have FIRDocumentReference

Time:11-20

I'm not sure what triggered this issue - my project was working as desired. It appears that a document was created in my Firestore database that is nil in all fields except for the FIRDocumentReference, which appears to be a memory address. I was able to find this document by running the query against the database with all fields in the receiving struct converted to optional and then filtering the resulting array for nil values. If I don't convert the struct's fields to optional, it causes the query to fail with the error message: "The data couldn't be read because it is missing."

I can also avoid this error by limiting the query to 300 documents. For example:

citiesRef
    .whereField("population", isGreaterThan: 100)
    .limit(to: 300) 

When I raised the limit to 400 (Note: there are approximately 2700 total documents.) it gives me the same error. So, my guess is that this nil document is hiding somewhere between documents 300 and 400.

I tried going into Firebase Console and deleting the document directly, but I can't find such a document in the console, even by going through, document by document.

What would be the best course of action?

CodePudding user response:

I'm not sure about this is working as expected but, If I were you I would try this in a view for one time running like a script.;

Run a query that checks null fields and if there is one or more null fields in a document, I'll delete it.

Just for example; Run a query to fetch documents that has more than one null value;

citiesRef.whereField("state", isEqualTo: "CO").whereField("name", isEqualTo: "Denver").getDocuments { (querySnapshot, err) in
    if let err = err {
        print("Error getting documents: \(err)")
    } else {
        for document in querySnapshot!.documents {
            db.collection("cities").document(document.documentID).delete()
        }
    }

CodePudding user response:

The answer turned out to be as simple as isolating the null document and calling .delete() on it. Once I did that, I reverted the corresponding struct with its optional values back to non-optional (as well as reversing the changes I had to make elsewhere) using git.

Without those modifications, the query would error out and I wouldn’t be able to access the document. It was tedious, but effective.

  • Related