I'm currently doing a proof of concept for an Android app with the new Firestore as backend/db. I need to fetch a bunch of documents by their id (they are all in the same collection)
Right now, I'm looping thru the id list and fetching them one by one and storing them in a list which in turn updates a RecycleView in the app. This seems to be a lot of work and it does not perform very well.
What is the correct way to fetch a list of documents from Firestore without having to loop all the ids and getting them one by one?
Right now my code looks like this
for (id in ids) {
FirebaseFirestore.getInstance().collection("test_collection").whereEqualTo(FieldPath.documentId(), id)
.get()
.addOnCompleteListener {
if (it.isSuccessful) {
val res = it.result.map { it.toObject(Test::class.java) }.firstOrNull()
if (res != null) {
testList.add(res)
notifyDataSetChanged()
}
} else {
Log.w(TAG, "Error getting documents.", it.exception)
}
}
}
New document with same ID should not be allowed in the same collection. It should be possible to fetch an already existing document from a previous import.
Starting with… in queries! With the in query, you can query a specific field for multiple values (up to 10) in a single query. You do this by passing a list containing all the values you want to search for, and Cloud Firestore will match any document whose field equals one of those values.
How do I get documents from Firebase? getFirestore() → Firestore Database. doc() → It takes references of database, collection name and ID of a document as arguments. getDoc() → getDoc() query gets data of a specific document from collection based on references mentioned in the doc() method.
This is the way i'm using until they will add this option
I made that with AngularFire2 but also with the rxfire libary is the same if you are using react or vue. You can map the null items before subscribing if there are some documents that deleted.
const col = this.fire.db.collection('TestCol');
const ids = ['a1', 'a2', 'a3', 'a4'];
const queries = ids.map(el => col.doc(el).valueChanges());
const combo = combineLatest(...queries)
.subscribe(console.log)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With