Reputation: 237
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")
});
});
Upvotes: 6
Views: 8302
Reputation: 1767
Maybe this won't work in all solutions but it works for me so far...
Obviously this is a single instance of DocumentData but you should be able to adapt to other scxenarios
const companyDocumentSnapShot2 = await db.doc(<document path>).get()
const companyDocumentDocumentData2 = companyDocumentSnapShot2.data() as FirebaseFirestore.DocumentData
return JSON.stringify(companyDocumentDocumentData2)
then on the client I use Moshi (Android) to convert the JSON to a class)
val moshi = Moshi.Builder().build()
val jsonAdapter = moshi.adapter(CompanyRecord::class.java)
val instance = jsonAdapter.fromJson(jsonString)
Upvotes: 0
Reputation: 317372
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.
Upvotes: 4