'Flutter - Can't get collection from firestore
_getLatestCompletedWorkout() async {
try {
QuerySnapshot workouts;
workouts = await FirebaseFirestore.instance
.collection('users')
.doc(FirebaseAuth.instance.currentUser!.uid)
.collection('workouts')
.get();
for (var workout in workouts.docs) {
print('WORKOUT = ');
print(workout);
}
.....
What I really need is to get the last document saved; but before that I am just trying to fetch the "workouts" collection; the workouts.docs list always has 0 items. There are 2 items in the DB. What is wrong with this code? Also how to get the last saved item?
Solution 1:[1]
As mentioned by Frank :
You can refer Alex answer here :
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.
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 }; }); });
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 |