Moshe Shaham
Moshe Shaham

Reputation: 15974

Getting the latest document in a collection

I have a collection of item. When I listen to it, I see I'm getting all the items all the time. I only need the latest document, I need to respond when a new document is added. I tried to limit the query like this:

    this.itemsCollection = this.afs.collection('games').doc(gameId)
        .collection('hands', ref => ref.orderBy('started').limit(1));
    this.items = this.itemsCollection.valueChanges();
    this.items.subscribe((hands: Hand[]) => {
      console.log('got hand ', hands);
    });

sadly, it doesn't work. I'm not getting any items when a new item is added. When I remove the limit function, I'm getting all the items every time...

Upvotes: 1

Views: 39

Answers (1)

tzovourn
tzovourn

Reputation: 1321

The simplest way to achieve this is to add a Date property to each object in your collection, then simply query it according to this new property descending and call limit(1) function. You may check the documentation on how to "Order and limit data with Cloud Firestore" and "Get data with Cloud Firestore"

The idea is the following:

db.collection("YourCollection")
  .orderBy('Date', 'desc')
  .limit(1).get()
})

Let me know if this is helpful.

Upvotes: 1

Related Questions