Javascript Firebase-获取最新文档

Javascript Firebase-获取最新文档,javascript,google-cloud-firestore,Javascript,Google Cloud Firestore,我有一个节点服务器正在运行,我想在那里侦听集合更新并获取添加的数据。 我的解决方案是使用db.collection(“posts”).onSnapshot收听更新,并按日期获取最新的订单 db.collection("posts").onSnapshot(async () => { const newPost = await db .collection("posts") .orderBy("date", &q

我有一个节点服务器正在运行,我想在那里侦听集合更新并获取添加的数据。 我的解决方案是使用db.collection(“posts”).onSnapshot收听更新,并按日期获取最新的订单

db.collection("posts").onSnapshot(async () => {
  const newPost = await db
    .collection("posts")
    .orderBy("date", "desc")
    .limit(1)
    .get()
    .data();
  console.log(newPost);
});
但是.data()不是函数,所以我不知道如何检索数据。我做了一点除错,在对象中找不到任何键,这些键可以给我文章中的数据

这是它在没有.data()的情况下返回的结果


您的代码必须首先等待
get()
的结果,然后进入返回的文档以查找文档数据。请注意,QuerySnapshot包含零个或多个文档,您需要使用其API来确定是否返回了任何文档。即使您认为它只会返回一个文档,您仍然需要进入结果集以找到那一个文档

  const newPost = await db
    .collection("posts")
    .orderBy("date", "desc")
    .limit(1)
    .get();
  // newPost is a QuerySnapshot
  if (newPost.size > 0) {
    const data = newPost.docs[0].data();
    // do what you want with the document data
  }
  else {
    // figure out what you want to do if no documents were queried
  }

谢谢你,我想我检查过了,但显然没有。
  const newPost = await db
    .collection("posts")
    .orderBy("date", "desc")
    .limit(1)
    .get();
  // newPost is a QuerySnapshot
  if (newPost.size > 0) {
    const data = newPost.docs[0].data();
    // do what you want with the document data
  }
  else {
    // figure out what you want to do if no documents were queried
  }