I use firebase firestore to store multiple documents with auto-generated IDs. In my code I generate a random ID and then query the database with "isGreaterThanOrEqualTo: _randomIndex" to read 3 random documents. My issue is: My database is not very big yet. When I use this approach, I sometimes get 0, only 1 or only 2 documents back although I iterate through it 3 times to get 3 documents. I think the reason is because of the limited amount of data there is sometimes no "greaterThanOrEqualTo" ID in my database so I get nothing back.
How can I enhance my code to get always 3 documents back?
My Code:
String getRandomGeneratedId() {
const int AUTO_ID_LENGTH = 20;
const String AUTO_ID_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const int maxRandom = AUTO_ID_ALPHABET.length;
final Random randomGen = Random();
String id = '';
for (int i = 0; i < AUTO_ID_LENGTH; i++) {
id = id + AUTO_ID_ALPHABET[randomGen.nextInt(maxRandom)];
print('RandomID is $id');
}
return id;
}
Future<List> getData() async {
List<Recipe> dataList = [];
CollectionReference myRef = FirebaseFirestore.instance.collection('recipes');
// Retrieves 3 random data in a loop
for (int i = 0; i < 3; i++) {
// generate a random index based on the list length
// and use it to retrieve the element
String _randomIndex = getRandomGeneratedId();
print('RandomIndex is $_randomIndex');
QuerySnapshot querySnapshot = await myRef
.where('id', isGreaterThanOrEqualTo: _randomIndex)
.orderBy('id', descending: false)
.limit(1)
.get();
print('QUERYSNAP is $querySnapshot');
dataList.addAll(querySnapshot.docs.map((d)=> Recipe.fromJson(d.data() as Map<String, dynamic>)));