Reputation: 172
What I want to do: I want to get the first document from my collection in the Firestore, which should be order from Z-A when it comes to "description" in the document.
The problem: It tells me "No such document!". Although it should output me 1 document.
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);
});
};
Upvotes: 3
Views: 3488
Reputation: 317412
Your variable doc
is a QuerySnapshot object (not a 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.
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. 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.
Upvotes: 6