【问题标题】:Firestore get a post title using async awaitFirestore 使用异步等待获取帖子标题
【发布时间】:2021-03-04 20:07:01
【问题描述】:

我正在尝试从 firestore 获取帖子标题,但不知何故我无法弄清楚如何使用 async await 来完成。

async getVideo(id) {
  var self = this;
  const ref = this.$fire.firestore
    .collection("posts")
    .where("ytid", "==", id)
    .orderBy("createdAt", "desc");
  try {
    let post = await ref.get();
    console.log(post.data());
  } catch (e) {
    console.log(e);
  }
}

我试图控制日志 post.data() 但它说 post.data() 不是一个函数。 任何帮助将不胜感激。

【问题讨论】:

  • 你现在有什么问题?请编辑问题以包含您的调试信息。

标签: javascript firebase vue.js google-cloud-firestore nuxtjs


【解决方案1】:

当你调用ref.get() 时,你会得到一个QuerySnapshot 对象。此对象包含零个或多个 DocumentSnapshot 对象,这些对象包含来自查询结果的数据。 QuerySnapshot 没有名为data() 的方法。您必须使用提供的 API 迭代文档以获取 DocumentSnapshots:

const qsnapshot = await ref.get();
qsnapshot.forEach(doc => {
    const data = doc.data();
    console.log(data);
})

【讨论】:

    【解决方案2】:

    您正在检索多个文档,因此 post 将是没有 data() 方法的文档的快照。

    您需要遍历快照以访问各个文档。

    请参阅https://firebase.google.com/docs/firestore/query-data/get-data#get_multiple_documents_from_a_collection 以获取快速指南或https://googleapis.dev/nodejs/firestore/latest/QuerySnapshot.html 以获取QuerySnapshot 类型的完整参考。

    【讨论】:

      猜你喜欢
      • 2020-05-14
      • 2019-04-20
      • 2018-08-23
      • 2018-05-04
      • 2021-07-12
      • 2022-07-06
      • 2020-10-17
      • 2020-10-20
      • 1970-01-01
      相关资源
      最近更新 更多