【问题标题】:How to get firestore reference type in typescript?如何在打字稿中获取firestore引用类型?
【发布时间】:2020-12-24 19:34:30
【问题描述】:

我有以下代码:

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()

由于某种原因,我似乎无法找到适合配料的类型。 我得到的错误是:

Error: Error serializing .recipes[0].ingredients[0].ingredient returned from getStaticProps in "/".

firestore 中的typescript 中定义引用数组类型的方法是什么?

另外,如果我这样做(只是为了调试)

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
}

为什么我得到路径未定义?

【问题讨论】:

  • 哪行代码会产生该错误?我根本看不到任何序列化任何东西的代码。我也看不到您在哪里使用“食谱”类型。我建议编辑问题以添加所有相关代码,并解释您希望代码做什么而不是生成此错误。
  • @DougStevenson 添加了更多代码。但是,可以只是一个定义类型的简单调用,不需要写出来,因为已经有一个调用函数。例如 const 食谱:Recipes[] = await getAllRecipes()
  • 这是您正在运行的所有代码吗?我仍然没有看到任何序列化。哪一行代码导致错误?
  • @DougStevenson 最后一行,注意标签包含 Nextjs,所以错误来自调用 await getAllRecipes() 并从 getStaticProps 序列化。我更新了完整的错误消息
  • 您的文档是什么样的?那将是实际数据,对吧?

标签: typescript firebase google-cloud-firestore next.js


【解决方案1】:

我强烈怀疑 DocumentReference 对象(它是一个引用其他 Firestore 对象的复杂对象)的默认 toJSON 序列化不会按照您想要的方式工作。如果您希望调用者有一个 DocumentReference,您将不得不使用其path 属性将每个转换为字符串路径,然后使用Firestore.doc(path) 将路径重建为引用。 TypeScript 类型根本不重要——它只是围绕核心对象集的一层理解。

【讨论】:

  • 如何获取路径?当我输入上面的代码时,我没有得到路径,它们由于某种原因是未定义的?
  • 正如我在回答中链接的那样,如果您有 DocumentReference 对象,则可以使用其路径属性。我无法解释为什么你在某处有一个未定义的值。那根本不会事件序列化。您必须深入研究文档快照并以某种方式获取实际的参考对象。
猜你喜欢
  • 1970-01-01
  • 2020-05-09
  • 1970-01-01
  • 2019-07-25
  • 1970-01-01
  • 1970-01-01
  • 2020-11-10
  • 2022-01-25
  • 1970-01-01
相关资源
最近更新 更多