BB Design
BB Design

Reputation: 705

Firestore retrieve a single document from a collection based on orderBy and limit without forEach

My Javascript looks similar to this:

firestoredb.collection('abc')
    .doc('bcd')
    .collection('cde')
    .orderBy('bid', 'desc')
    .orderBy('timestamp', 'asc')
    .limit(1)
    .get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            console.log(doc.data().bid);
        });
    });

Is it possible to retrieve doc.data().bid without the forEach statement and maybe without the querySnapshot variable? Since I know there will only be one record in this case. Or is forEach still the recommended way to do this? Everything else I have tried results in an error message. I am mostly wondering if there is a simpler way to code this.

Upvotes: 1

Views: 103

Answers (2)

Kundan
Kundan

Reputation: 1952

I hope the code below helps.

firestoredb.collection('abc')
  .doc('bcd')
  .collection('cde')
  .orderBy('bid', 'desc')
  .orderBy('timestamp', 'asc')
  .limit(1)
  .get()
  .then(function(doc) {
     console.log(doc.data().bid);
   }

Upvotes: 0

DVN-Anakin
DVN-Anakin

Reputation: 1772

Couldn't fit the answer into a comment. Is this what you were looking for?

firestoredb.collection('abc')
    .doc('bcd')
    .collection('cde')
    .orderBy('bid', 'desc')
    .orderBy('timestamp', 'asc')
    .get()
    .then(querySnapshot => console.log(querySnapshot.docs[0].data().bid));

Upvotes: 2

Related Questions