-
In my flutter/dart app, I have a list of IDs from document (of the same collection) that I want to retrieve from FireStore. I am trying to do the following: But ".doc()" won't accept a list as a parameter for the document ID to look for. I tried with the "where" method like this: But it won't work since the "id" isn't a field in the documents (it is their name/identifier). The only two solutions I can think about are:
The third one (ideal IMO) would be to enable .doc to accept lists/arrays, so you can search for a list of documents you know the identifier of. Am I missing something? Does anybody know any other solution? THANKS! (I have asked the same question here) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I found a solution here! So adapting it to my case it looks like this: Be aware that there is a limit of 10 to the number of values/IDs you can use in the search. |
Beta Was this translation helpful? Give feedback.
-
If you need more than 10 ids. First create a function to fetch by ids: Future<List<Book>> _getBooksByIds(ids) {
return _instance
.collection('books')
.where(FieldPath.documentId, whereIn: ids)
.get()
.then((QuerySnapshot snapshot) {
return snapshot.docs.map((DocumentSnapshot doc) => BookModel.fromSnapshot(doc)).toList();
});
}
Then split by 10 your ids ids = ['id1', 'id2'...'id11'];
final idsBy10 = [
for (var i = 0; i < ids.length; i += 10)
ids.sublist(i, min(i + 10, ids.length))
]; Then run multiple requests and merge their results: Future.wait<List<Book>>(idsBy10.map((ids) => _getBooksByIds(ids)))
.then((listOfLists) => listOfLists.expand((l) => l).toList()); Please share If you have an alternative solution shorter than mine. I would be glad to use it. |
Beta Was this translation helpful? Give feedback.
I found a solution here!
So adapting it to my case it looks like this:
await FirebaseFirestore.instance.collection('groups').where(FieldPath.documentId, whereIn: [id1, id2, id3, id4]).get();
Be aware that there is a limit of 10 to the number of values/IDs you can use in the search.