Can you query data based on the DocumentReference?

I have a field in my document called categoryRef which lives in a collection called comments. This field is a reference field. So an example piece of data for this would be sports/ASFFEHGWRHTTVR
This comment references a category in the sports collection. How do I query all the comments that have this reference sports/ASFFEHGWRHTTVR ??
Can that be done in swift?

Just to clarify, “sports” is the collection name and “ASFFEHGWRHTTVR” is the contents of a property in sports named category. Is that correct?

If so then you can query all documents from that sports collection where the field name is category and the contents of that field is equal to “ASFFEHGWRHTTVR”

The query code would be something like this:

let db = Firestore.firestore()

let query = db.collection("sports").whereField("category", isEqualTo: "ASFFEHGWRHTTVR")
query.getDocuments { snapshot , error in
    guard error == nil else { return }
    if let snapshot = snapshot {
        for doc in snapshot.documents {
            // Do whatever you want to do
        }
    }
}

let me know if I have understood you question correctly.

That is correct, however if my var is a reference data type from firebase, do I need to split that string to do a query call or can I used that string?

var x:DocumentReference
value of x is sports/ASFFEHGWRHTTVR

I can do a split ("/") on the x.path string to do the query below
let query = db.collection(“sports”).whereField(“category”, isEqualTo: “ASFFEHGWRHTTVR”)

My question is can I use that reference in a query without spitting it?

@mursta

You will have to split the string so that you can deal with the two parts separately. Something like this:

let categoryRef = "sports/ASFFEHGWRHTTVR"
let componentsArray = categoryRef.components(separatedBy: "/")
let collection = componentsArray.first
let category = componentsArray.last

Then in the query you could do something like this:

let query = db.collection(collection).whereField("category", isEqualTo: category)

Ok thank you. That is what I assumed, but wanted to make sure.

Thank you!

1 Like