Home > Net >  How to retrieve document data in Firebase without knowing collection name?
How to retrieve document data in Firebase without knowing collection name?

Time:06-24

The structure of my Firebase data is <collection>/<document>.

I know the name of the document, how can I access its data without specifying the collection name (unknown).

Some state that a Snapshot is needed and then getParent() can be called, the problem is in order to obtain a Snapshot you need the name of the collection.

The following works:

FirebaseFirestore.getInstance.collection("Fruit").doc("Apples").get()

Suppose we don't know that the collection's name is "Fruit", how can we still access the Document's data OR how can we retrieve its associated collection name?

CodePudding user response:

As I said in comments, if all you know is the string ID of a document, there is no way to know if it exists in any collection. It's important to know that there can be any number of collections with a document of a particular ID - the IDs are not unique across the entire database.

If you want to know if a document exists in a collection, you have to do exactly what you are showing now: get the document and check the snapshot to see if it exists. There are no workarounds for this. If you are storing these IDs somewhere, consider also storing the name of the collection (or the full path to the document) so that you have a reliable way of getting it back.

  • Related