简体   繁体   English

从文档顺序中获取第一个 Firestore 文档 (Node.js)

[英]Get first Firestore document from an order of documents (Node.js)

What I want to do: I want to get the first document from my collection in the Firestore, which should be order from ZA when it comes to "description" in the document.我想要做什么:我想从我在 Firestore 中的集合中获取第一个文档,当涉及到文档中的“描述”时,应该从 ZA 订购。

The problem: It tells me "No such document!".问题:它告诉我“没有这样的文件!”。 Although it should output me 1 document.虽然它应该输出我 1 个文件。

Here is the code:这是代码:

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);
});

};

Your variable doc is a QuerySnapshot object ( not a DocumentSnapshot).您的变量doc是一个QuerySnapshot对象(不是DocumentSnapshot)。 As you can see from the API documentation, it doesn't have a property called exists , so if (!doc.exists) will always be true.正如您从 API 文档中看到的那样,它没有名为exists的属性,因此if (!doc.exists)将始终为真。

Since a QuerySnapshot object always accounts for the possibility of containing more than one document (even if you specify limit(1) ), you still have to check the size of its result set to know see how many documents you got.由于 QuerySnapshot 对象总是考虑包含多个文档的可能性(即使您指定limit(1) ),您仍然必须检查其结果集的大小以了解您获得了多少文档。 You should probably do this instead:你可能应该这样做:

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

Note also that there is no need to use then/catch if you are using await to capture the result of the query from the returned promise.另请注意,如果您使用 await 从返回的承诺中捕获查询结果,则无需使用 then/catch。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM