Get last created document in a Firebase Firestore collection

后端 未结 1 775
小鲜肉
小鲜肉 2020-12-07 03:41

Is there any way to get last created document in Firebase Firestore collection? My requirement is when user signed I have to add a document in a collection named \'history\'

相关标签:
1条回答
  • 2020-12-07 04:07

    Is there any way to get the last created document in Firebase Firestore collection?

    Yes, there is! 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. That's it!

    As @eyyo mentioned in his comment, here is a concrete example. Assuming that your database schema looks like this:

    Firestore-root
      |
      --- history (collection)
            |
            --- docId (document)
                 |
                 --- date: June 24, 2020 at 6:46:25 PM UTC+3
                 |
                 --- //Other properties
    

    This is the required query:

    this.historyRef = afs.collection<History>('history', ref => ref.orderBy('date', 'desc').limit(1));
    this.history = this.historyRef.snapshotChanges().map(actions => {
        return actions.map(a => {
            const data = a.payload.doc.data() as Hisotory;
            const docId = a.payload.doc.id;
            return { docId, ...data };
        });
    });
    
    0 讨论(0)
提交回复
热议问题