Reputation: 51
I'm working on a project using Google firebase firestore. I wanna implement a filter on my search for users. Imagine the search for only active users with a checkbox which users can select.
let db = Firestore.firestore()
let reference = db.collection("users").limit(to: 20)
//FILTER
if showOnlyActiveUsersBtn.isSelected {
reference.whereField("active", isEqualTo: true)
}
reference.getDocuments(completion: {(querySnapshot, error) in
.....
})
I expected this would return the result with only users who have the field "active: true", however, it returned the same list as the query without the filter... if I write like:
let db = Firestore.firestore()
let reference = db.collection("users").limit(to: 20).whereField("active", isEqualTo: true)
reference.getDocuments(completion: {(querySnapshot, error) in
.....
})
It returns the result I expected first. I don't have any idea why my filter doesn't work. How can I add logical "AND" condition with user-friendly way?
Upvotes: 1
Views: 1979
Reputation: 317828
Firestore Query objects are immutable, meaning that they can never be modified after they are created. In your code, you aren't remembering the new query you built with whereField
. Instead, you need to build a new Query object on top of an existing query, and remember the new one:
let db = Firestore.firestore()
var reference = db.collection("users").limit(to: 20)
if showOnlyActiveUsersBtn.isSelected {
// build a new query using the old query, reassign to reference
reference = reference.whereField("active", isEqualTo: true)
}
reference.getDocuments(completion: {(querySnapshot, error) in
.....
})
If you don't like using var
instead of let
, I'm sure you can find a way to rework this sample. In any event, you will need to remember the new query returned by whereField
, and use that to call getDocuments
.
Upvotes: 13