I am not really sure that this is the best way to do this, but when putting just a regular array, I was not returning anything.
I have a firebase collection that looks something like this in Swift:
struct Tournament: Identifiable, Codable, Equatable, Hashable {
var playersUID: [String] = []
}
I have an array of UIDs that I want to query against my Player documents
struct Player: Identifiable, Codable, Equatable, Hashable { }
I am trying to pass the playersUID Array into searchPlayers() but I think instead of taking each value, it is trying to give the entire array into the search function:
func searchPlayers() async {
do {
let documents = try await Firestore.firestore().collection("Players")
.whereField("playersUID", isGreaterThanOrEqualTo: tournament.playersUID).
.whereField("playersUID", isLessThanOrEqualTo: "\(tournament.playersUID)\u{f8ff}")
.getDocuments()
let player = try documents.documents.compactMap { doc -> Player? in
try doc.data(as: Player.self)
}
await MainActor.run(body: {
fetchedPlayers.append(contentsOf: player)
})
}
that was one way... the other way I tried this was using a for-loop:
do {
let lastIndex = Int(tournament.playersUID.last!) ?? 0
for i in 0...lastIndex {
let documents = try await Firestore.firestore().collection("Players")
.whereField("playersUID", isGreaterThanOrEqualTo: tournament.playersUID[i])
.whereField("playersUID", isLessThanOrEqualTo: "\(tournament.playersUID[i])\u{f8ff}")
.getDocuments()
let player = try documents.documents.compactMap { doc -> Player? in
try doc.data(as: Player.self)
}
await MainActor.run(body: {
fetchedPlayers.append(contentsOf: player)
})
}
} catch {
print(error.localizedDescription)
}
I really don't know what I am doing wrong here. Is there a unique function that Firebase gives for querying?
Tournament.playersUIDis an array and you pass.whereField("playersUID", isGreaterThanOrEqualTo: tournament.playersUID), you're indeed comparing the full array in your code with the full array in the database. What other operation are you trying to execute here?Tournament.playersUID. Just for conformation, I will not have to use a for-loop right?playersUIDcontains exactly the same values astournament.playersUID, you can use.whereField("playersUID", isEqualTo: tournament.playersUID). For this to work it is important though that you have the array elements in the exact same order in both arrays.array-contains) and then performing the other checks client-side. There is noarray-contains-alloperator, which what you'd need for this. I linked a question that shows how to implement this use-case based on a map, instead of an array.