Get last created document in a Firebase Firestore collection

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'; When the user signed out I want to update that document with a field called 'signout'; So if i get the lastly added document it is very easy to update. Is there any way to do this?


Solution 1:

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