Reputation: 338
I have the following code:
import { DocumentReference } from '@firebase/firestore-types'
export type Recipe = {
author: string
title: string
ingredients: {
quantity: number
ingredient: DocumentReference["path"]
}[]
instructions: string[]
}
export const getAllRecipes = async() => {
const snapshot = await db.collection('recipes').get()
const data = snapshot.docs.map(doc => doc.data())
return data
}
const recipes: Recipe[] = await getAllRecipes()
I for some reason can't seem to get the type right for the ingredients. The error I got is:
Error: Error serializing .recipes[0].ingredients[0].ingredient returned from getStaticProps in "/".
What is the way to define the type on array of references from firestore
in typescript
?
Also, if I do (just for debugging)
export const getAllRecipes = async() => {
const snapshot = await db.collection('recipes').get()
const data = snapshot.docs.map(doc => {
const docData = doc.data()
const {ingredients} = docData
ingredients.map((ingredient: DocumentReference) => {
const jsonIngredient = ingredient.path
console.log(jsonIngredient)
})
return docData
})
return data
}
Why do I get path is undefined?
Upvotes: 2
Views: 6374
Reputation: 317412
I strongly suspect that the default toJSON serialization of a DocumentReference object (which is a complex object with references to other Firestore objects) just isn't going to work the way you want. If you want the caller to have a DocumentReference, you're going to have to convert each one into a string path using its path property, then rebuild the path into a reference using Firestore.doc(path). The TypeScript type doesn't matter at all - it is simply a layer of understanding around core set of objects.
Upvotes: 1