Fetch multiple documents by id in Firestore

2019-07-04 11:56发布

问题:

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)
                    }
                }
    }

回答1:

Firestore does not currently support query by IDs.

According to AngularFirebase, this is in the roadmap for development in the future, but its not official:

Keep in mind, Firestore is still in beta. Firebase engineers hinted at some really cool features on the roadmap (geo queries, query by array of ids) - I’ll be sure to keep you posted :)



回答2:

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)