'Update a field in the last document in Firestore collection Flutter

I am trying to update a field in the last document in the Firestore collection. My updating method is below:

updateHours() {
    return usersRef.doc(firebaseAuth.currentUser!.uid).collection('posts')
        .orderBy('datePublished', descending: true)
        .limit(1).get().then((querySnapshot) {
          return querySnapshot.docs.map((e) {
        usersRef
            .doc(firebaseAuth.currentUser!.uid).collection('posts')
            .doc(e.reference.id)
            .update({"totalTime": FieldValue.increment(1)});
       });
     });
    }

This does not work. If I use .forEach(), then all documents get updated. So, how to update only the last document field?



Solution 1:[1]

To be able to update the totalTime field inside the last document, please use the following lines of code:

void updateHours() async{
    CollectionReference postsRef = usersRef
               .doc(firebaseAuth.currentUser!.uid)
               .collection('posts');
    QuerySnapshot query = await postsRef.orderBy('datePublished', descending: true)
               .limit(1)
               .getDocuments();

    query.documents.forEach((doc) {
        doc.reference.updateData({"totalTime": FieldValue.increment(1)});
    });
}

Don't forget that Firebase APIs are asynchronous, and you need to wait for the data until it becomes available.

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 Alex Mamo