'AngularFIre: LImit to 10 most recents registers

I have a query on firebase, but I want to show just the most 10 recents registers instead all of them

my code is:

  videos: Observable<any[]>;

  constructor(firestore: AngularFirestore,) {

    this.videos = firestore.collection('videos').valueChanges();

  }

Someone know the best way to do that?

Thanks!



Solution 1:[1]

You can pipe your observable and slice the 10 recent items using map operator from 'rxjs', something like

  videos: Observable<any[]>;

  constructor(firestore: AngularFirestore,) {

    this.videos = firestore.collection('videos').valueChanges().pipe(
      map(videos => videos.slice((videos.length - 10), videos.length))
    )

  }

Solution 2:[2]

Too save money in the production you need to save information about time when document was created. This will allow you to create query requests that will deliver exact amount of documents and in special order you need.

videos: Observable<any[]>;
        
          constructor(firestore: AngularFirestore,) {
        
          async getVideos() {
            this.videos = await this.firestore.collection('videos', ref => 
            ref.orderBy('createdAt').limit(10)).valueChanges();
            return this.videos
          }
        }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Owen Kelvin
Solution 2 Andrew Kyshkan