How do I query a user’s info in Firestore if all my document IDs are auto-generated?

Tags: , , ,



All of the examples I’m finding online have very simple document IDs, but what do you do if you’re auto-generating all your IDs (as the docs say you should)? For example, I want to query the date when the user was created. The document ID for this is below, but I’ve just copy-pasted it from the Firestore console. How would I know the document ID so that I may query any user’s info? Note that I will be have a users, groups, usergroups, etc… There will be quite a few collections, each using the auto-ID feature. I would need to be able to update any row in any collection.

val docRef = db.collection("users").document("9AjpkmJdAdFScZaeo8FV45DT54E")
        docRef.get()
            .addOnSuccessListener { document ->
                if (document != null) {
                    Log.e("Query", "Data: ${document.data}")
                } else {
                    Log.e("Query", "Document is null")
                }
            }
            .addOnFailureListener { exception ->
                Log.e("Query", "Failure")
            }

Answer

If you have data to query, that should all be stored as fields in the documents. Don’t put that data in the ID of the documents – use field values.

You can filter documents in a collection using “where” clauses as shown in the documentation. What you’re showing here isn’t enough to go with in to make specific recommendations. But you definitely want to think about your queries ahead of time, and model your data to suit those queries.

If you need to update a document, you must first query for it, then update what you find from the query. This is extremely common, as Firestore does no provide any SQL-like “update where” queries that both locate and update data in the same command.



Source: stackoverflow