Firestore 使用异步等待获得 post 标题

Firestore get a post title using async await

我正在尝试从 firestore 获取 post 标题,但不知何故我不知道如何使用 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() 不是函数。 任何帮助将不胜感激。

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

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

有关 QuerySnapshot 类型的完整参考,请参阅 https://firebase.google.com/docs/firestore/query-data/get-data#get_multiple_documents_from_a_collection for a quick guide or https://googleapis.dev/nodejs/firestore/latest/QuerySnapshot.html

当您调用包含查询结果数据的 ref.get(), you will get a QuerySnapshot object. This object contains zero or more DocumentSnapshot 对象时。 QuerySnapshot 没有名为 data() 的方法。您将必须使用提供的 API 迭代文档以获取 DocumentSnapshots:

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