【问题标题】:Get first Firestore document from an order of documents (Node.js)从文档顺序中获取第一个 Firestore 文档(Node.js)
【发布时间】:2020-10-03 23:19:57
【问题描述】:

我想做的事:我想从 Firestore 中的收藏中获取第一个文档,当涉及到文档中的“描述”时,它应该是 Z-A 订购的。

问题:它告诉我“没有这样的文件!”。虽然它应该输出我 1 个文档。

代码如下:

getPost();

async function getPost() {

const postRef = db.collection('posts');
const doc = await postRef.orderBy('description', 'desc').limit(1).get()
.then(doc => {
  if (!doc.exists) {
    console.log('No such document!');
  } else {
    console.log('Document data:', doc.data());
  }
})
.catch(err => {
  console.log('Error getting document', err);
});

};

【问题讨论】:

    标签: javascript node.js firebase google-cloud-firestore


    【解决方案1】:

    您的变量 docQuerySnapshot 对象(不是 DocumentSnapshot)。从 API 文档中可以看到,它没有名为 exists 的属性,因此 if (!doc.exists) 将始终为 true。

    由于 QuerySnapshot 对象总是考虑包含多个文档的可能性(即使您指定 limit(1)),您仍然需要检查其结果集的大小以了解您获得了多少文档。您可能应该这样做:

    const querySnapshot = await postRef.orderBy('description', 'desc').limit(1).get()
    if (querySnapshot.docs.length > 0) {
        const doc = querySnapshot.docs[0];
        console.log('Document data:', doc.data());
    }
    

    另请注意,如果您使用 await 从返回的 Promise 中捕获查询结果,则无需使用 then/catch。

    【讨论】:

      猜你喜欢
      • 2021-09-11
      • 2020-12-29
      • 2018-09-03
      • 2022-01-20
      • 2021-06-24
      • 2018-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多