Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a Firestore Document Reference to JSON data in TypeScript

I have a collection of firestore documents which contain an array of reference objects, referencing documents found in another firestore collection. When i attempt to fetch a document and convert it to JSON data i get an error : "TypeError: Converting circular structure to JSON". The issue seems to be with the type of the firestore reference? Im new to typescript and am not sure what the issue is as everything works when i exclude the array of references. (Also the references are not actually circular, they reference completely separate documents that are not related)

Here is the code used to get the document

interface PlaylistData {
    name: String
    description: String
    coverImage: String
    tracks: [FirebaseFirestore.DocumentReference]
} 

export const getPlaylist = functions.https.onRequest((request, response) => {
    admin.firestore().collection("playlists")
    .doc('test').get()
    .then(function (snapshot){
        let data = <PlaylistData>snapshot.data()
        console.log(data)
        response.send(data)
    })
    .catch(error => { 
        console.log(error)
        response.status(500).send("ERROR")
    });
});
like image 501
Alec Barton Avatar asked Aug 09 '26 17:08

Alec Barton


1 Answers

You will have to process that data object to remove or convert the document references before passing it to send(). The DocumentReference objects have an internal structure that can't be effectively (or efficiently) serialized. Consider instead just serializing a string that can be used to reconstitute the reference on the client. I suggest simply using its path string property for that. On the client side, you can pass that string to firestore.document() or firestore.doc() to build up a local DocumentReference object again.

like image 179
Doug Stevenson Avatar answered Aug 12 '26 10:08

Doug Stevenson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!