Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

};
like image 821
Jan Swoboda Avatar asked Oct 28 '25 03:10

Jan Swoboda


1 Answers

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.

like image 111
Doug Stevenson Avatar answered Oct 29 '25 17:10

Doug Stevenson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!