Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore DocumentReference Serialization

I have a pojo which maps a firestore document. That document contains references to other documents of other collection.

class Game(var local: String? = null, var visitor: String? = null,
        var events: MutableList<DocumentReference> = mutableListOf(), var date: Date? = null): Serializable 

The problem is that DocumentReference isn't serializable. I've read that I can save the path as String and then create the object myself(FirebaseFirestore.getInstance().document(path)), but then in the firestore is no longer a field of type Reference.

So my question, Is this the good approach? Also, Does it matter that the field is a String rather than a Reference?

Regards, Diego

like image 415
niegus Avatar asked Sep 09 '25 23:09

niegus


1 Answers

So my question is, is this the good approach?

Yes it is. The most important part in a DocumenetReference is the string path. If you serialize that, you can reconstitute a DocumentReference object, very easy.

As the conclusion, if you need to serialize a DocumentReference object, use DocumentReference's getPath() method to get a literal String that represents the document's location in the database. To deserialize that path String back into a DocumentReference object, simply use FirebaseFirestore.getInstance().document(path).

Edit:

This implies that the field in the database is now a String instead of Reference.

That's right.

Does it matter? I suppose that being a Reference must have some type of advantage.

Yes, since now the property is of type a String, you cannot take advantage of what DocumentReference class provides anymore. But this is the workaround that can help you achieve what you want. String class is serializable while DocumentReference's is not.

like image 170
Alex Mamo Avatar answered Sep 12 '25 14:09

Alex Mamo